What is python and why do I care? (Click for video)
l python is an interpreted programming language used to provide instruction to the computer to as to get some job done
l A computer science student must know how to code a computer and make it execute according to her/his wish and python is the language of choice as it
n Is relatively easy to learn
n Has a huge supporting library
n comparatively fast and efficient
Def: token are the smallest individual unit in python language
Types:
1. keyword
2. Identifier
3. operator
4. Literal
Def: Reserved words in python that has specific meaning in the code and can not be changed by the programmer
Example: class, if , elif, for ,while, pass, try, except, import etc
Def: Basically they are names given to variable, function, lamda, class, data structure etc
Rules for Identifier declaration/creation:
1. Keywords can not be used as identifier (I.e while is invalid)
2. identifier can not start with number (I.e 1name is invalid) but numbers can be any where else(I.e name1 is valid)
3. No special symbol (like @, #, $, %, &, . ,* etc) can be used, only underscore can be used(I.e. _name_ is valid)
4. No limit on the number symbols used in identifier
Operator in python
Def: Operator is symbol that gives instructions for an operation(like sum, divide, multiply) to be performed between operands
Types:
1. Arithmetic Operator
2. Relational Operator
3. Assignment Operator
4. Logical Operator
5. Bitwise Operator
6. Membership Operator
7. Identity Operator
Arithmetic Operator: (Click here for Video Description)
Operator
|
Example
|
Remarks
|
+ (Addition)
|
10+5=15
‘a’+’b’=’ab’
[1,2,3]+[4,5,6]=[1,2,3,4,5,6]
|
Performs addition if two numbers
if string then performs concatenation
|
- (Subtraction)
|
10-5=5
5-10=-5
|
Normal subtraction
|
* (Multiplication)
|
10*5=50
‘a’*3=’aaa’
[1,2,3]*2=[1,2,3,1,2,3]
|
Normal multiplication but behaviour changes based on the data type of the operands
|
/ (Division)
|
10/5=2.0
|
all the output are in floating point type
|
% (Modulus)
|
10%5=0
10%3=1
|
Find the remainder and the output is of integer type
|
** (Exponent)
|
10**2=100
2.5**3=15.625
|
finds the power/Exponent of x raised to y
|
// (floor division)
|
5//2=2
9//2=4
9.0//2.0=4.0
|
returns the integer part of the quotient of division operation
|
Note: this group of operator performs an comparison or establish a relation between two operands. It usually returns a truth value I.e True/Value
Operator
|
Example
|
== (equality operator)
|
10==10 returns True
True==True returns True
|
< (less than operator)
|
10<15 returns True
|
> (greater than operator)
|
10>5 return True
|
<= (less than equal to operator)
|
checks if the operand is less than or equal to each other
|
>= (greater than equal to operator)
|
checks if the operand is grater than or equal to each other
|
!= (not equal to operator)
|
checks if the operands are not equal to each other
|
Note: This operator deals with the truth value( i.e. TRUE/FALSE) of the operands.
Note: In python each object has a truth value associated with it. The following is are considered to have False truth value:
1. None,
2. False,
3. Zero of any numeric type I.e 0, 0.0, 0j
4. any empty sequences, I.e. ‘ ‘, ( ), [ ]
5. empty mapping I.e. { }
Any other value is considered True
Operator
|
Example
|
Remarks
|
NOT (logical not operator)
|
not True is False
not 12 is False
|
this operator negates(reverses) the truth value
|
AND (logical and operator)
|
True and False is False
10 and 10 is 10
10 and 12 is 12
10 and -10 is -10
|
if both the operands are True then the output is True else False
Also it selects the value with higher truth value
|
OR (logical or operator)
|
True or False is True
10 or 10 is 10
10 or -10 is 10
10 or 12 is 12
|
if one of the operand is true then OR operator with select the operand with the truth value of highest truth value
|
Operator
|
Example
|
Remark
|
=
|
x=10
|
assign 10 to variable x
|
+=
|
x+=10
|
add the value 10 to the existing value of x and then assign it to x
|
-=
|
x-=10
|
subtract value 10 to the existing value of x and then assign it to x
|
*=
|
x*=10
|
multiply value 10 to the existing value of x and then assign it to x
|
/=
|
x/=10
|
divide value 10 to the existing value of x and then assign it to x
|
%=
|
x%=10
|
find the modulo of x%10 and then assign it to x
|
**=
|
x**=10
|
finds the exponent of x raised to 10 and then assign it to x
|
//=
|
x//=10
|
performs floor division on x with 10 and assign the value to x
|
Bitwise Operator
Note: This operator works on binary level I.e. each integer in converted to binary and the operation is done and then the result is returned in integer format again.
The operator present are &(bitwise and), |(bitwise or), ^(bitwise XOR), !(bitwise complement) . we will not discuss this operator in any more detail in here.
Note: These operator are used to check the presence/absence of an object (or variable loosely saying) in a sequence like String, List, Tuple, set etc
Operator
|
Example
|
Remarks
|
in
|
10 in [5,10,15,20] will give True
|
checks for the presence 10 in the list
|
not in
|
‘H’ not in ‘HELLO’ will give False
|
checks for the absence of H in HELLO
|
Note: performs the comparison between the identity of two variable or objects, there are two types is and not is
is
|
is not
|
a=10
b=10
c=20
print(a is b) this gives True
print(a is c) this gives False
|
a=10
b=10
c=20
print(a is not b) this gives False
print(a is not c) this gives True
|
Note: Operators can be combined but their sequence of execution depends on the operator precedence
Table of operator precedence in python(In decreasing order of precedence)*:
Note: all the operators in the same row has same precedence but the default evaluation order is from Left to Right
Operator
|
Description
|
Priority/Precedence
|
(expression..),[expression..],{key:value…}
{expression..}
|
parenthesized expression, list , dictionary , set
|
Highest
|
x[index],x[index:index]x(arguments),x.attributes
|
Slicing, function call, attribute reference
| |
**
|
Exponent
| |
*,@,/,//,%
|
Multiplication, matrix multiplication, division, floor division, remainder
| |
+, -
|
Addition and Subtraction
| |
<<,>>
|
left and right shift operator
| |
&
|
Bitwise AND
| |
^
|
Bitwise XOR
| |
|
|
Bitwise OR
| |
in, not in, is, not is, <,<=,>,>=,!=,==
|
Comparisons, including membership tests and identity tests
| |
not x
|
Boolean NOT
| |
and
|
Boolean AND
| |
or
|
Boolean OR
| |
if - else
|
Conditional expression
| |
lambda
|
Lambda expression
| |
=
|
Assignment
|
Lowest
|
Example of operator combination:
Expression
|
Result
|
10+20>12+10
|
True
|
10+20*3+10
|
80
|
(10+20)*(3+10)
|
390
|
True+10
|
11 (Bit of Type Casting is going on also)
|
10==10>7/2**1%5
|
Trues
|
x=10/2**3
print(x)
|
1.25
|
Literal in python
Note: literals are the values assigned to variables. the different types of literals are listed below
Types of literal
|
Example
|
Numeric Literal
(Numeric Literal are immutable)
|
a=0b1100 # Binary literal
b=100 # Decimal Literal
c=0o214 # Octal Literal
d=0x45A # Hexadecimal Literal
f1=3.14 # Float literal
f2=3e10 # Float literal written in scientific notation
cp=2+8j # Complex literal
|
String literal
(string literal is also immutable)
|
str1=”this is a string literal”
str2=”””this is a multiline
string”””
str3= ‘this is also\
a multiline\
string’
|
Boolean Literal
Note: True has as integer value of 1
and False has an integer value of 0
|
a=True
b=False
|
Literal Collection
|
days=[‘mon’,’tue’,’wed’] # List Literal
num=(12,13,14,15) #tuple literal
roll_nam={1:’jam’,2:’cristina’} #Dictionary literal
vowels = {'a', 'e', 'i' , 'o', 'u'} #set literal
|
None Literal
Note: ts is used to indicate something whose value is not known, its the legal empty value in python
|
value=None
|
Note: Comments are the information/documentation about the code and they don’t get executed
Types:
1. Single line comment: starts with ‘#’ and expands over a single line
#this is a single line comment
2. Multi-line comment *: starts with triple quotes, ends with triple quotes and expands over multiple line.
‘’’ this is
an example
of multiline comment’’’
*Note the idea of multiline comment is debatable and doesn’t have a universal acceptance
Note: usually programs are executed linearly I.e. from from top to bottom but by using control statement we can change this behaviour. The control structure are given below:
1. Conditional Statement
2. Looping/iterative statement
3. Jump Statement
Note: The piece of code gets executed only if the conditional statement evaluate to True else not.
Syntax:
if condition:
statement1
statement2
..
statement n
elif condition: #optional
statement3
statement4
…
statement n
else: #optional
statement5
statement6
…
statement n
Points to remember:
1. The conditional Statement should all ways evaluate to True or False, nothing else will work
2. if clause can be used alone without elif or else condition but elif and else have to used with if condition
3. elif takes a conditional expression but else does not
Example Program:
Question
|
A program to find if the entered number is positive, negative or zero
|
Program
|
num=int(input("Enter the number: "))
if num>0:
print("the entered number is positive")
elif num<0:
print("the entered number is negative")
else:
print("the entered number is zero")
|
Execution
|
Enter the number: -8
the entered number is negative
Enter the number: 5
the entered number is positive
|
Note: This construct is used to execute same piece of code over and over again based on a criteria. Any kind of Looping statement will have 3 parts 1. initialization, 2. Stopping condition, 3. loop count increment or decrements(I.e. state change). different language implement these 3 part in different types.
Python has looping constructs
1. for loop [used when we know how many times the loop will run]
2. while loop [used when we don’t know how many times the loop will run]
FOR LOOP:
Note: Usually used when the programmer is aware of all the parts of the loop and the number of loops it will do
Syntax:
for variable in a sequence: #Sequence can be a range function, list, tuple or an iter function etc
statement1
statement2
…
statement n
else: #gets executed when the for loop ends
statement3
statement4
…
statement n
Example Program:
Question
|
A program to print “in the for loop ” 5 times and also print “the loop ends” when the loop ends, using for loop
|
Program
|
for i in range(5):
print("in the for loop")
else:
print("the loop ends")
|
Execution
|
in the for loop
in the for loop
in the for loop
in the for loop
in the for loop
the loop ends
|
WHILE LOOP:
Note: this loop is used when the number of times the loop will run is not sure
Syntax:
initialization
while condition: #the loop continues till the condition is true
statement1
statement2
…
statement n
increment_statement #needed to move the loop to the next step. its absence may lead to infinite loop
else: #gets executed when the loop ends
statement3
statement4
…
statement n
Example Program:
Question
|
A program to print “in the while loop ” 5 times and also print “the loop ends” when the loop ends, using while loop
|
Program
|
i=1
while i<6:
print("in the while loop")
i +=1
else:
print("the loop ends")
|
Execution
|
in the for loop
in the for loop
in the for loop
in the for loop
in the for loop
the loop ends
|
NOTE: As we observe that its usually possible possible to interchange between for loop and while loop
Note: these are used to jump out of the normal flow of execution. break and continue are the jump statement
break
Note: it let lets the execution jump out of a block(I.e conditional , loops etc)
Example
Question
|
A program to find the 1st 4 odd numbers between 10 and 20
|
Program
|
num=0
for i in range(10,21):
if num==5:
break #the loop terminates when num ==5 is True
if i%2==0:
print(i ,end=’ ’)
num+=1
else:
num=0
|
Execution
|
10 12 14 16 18
|
continue
Note: based on condition makes the execution jump to the next iteration but doesn’t terminates the loop like beak statement
Example
Question
|
A program to find the odd numbers between 10 and 20
|
Program
|
for i in range(10,21):
if i%2==0:
continue #makes the loop go to next if the number is even else print it
print(i,' ', end=" " )
|
Execution
|
11 13 15 17 19
|
Empty Statement:
Note: Used in blocks of loops, conditional statement or function deceleration where we are not sure about the inner code and will add later in time.
Example
for i in range(10):
while True:
def func():
|
all these statement will throw error
|
for i in range(10):
pass
while True:
pass
def func():
pass
|
these are valid code and will not through error, but they are empty statement
|
Note: Variables in python are basically names that are associated to object. Now these objects can be literals, tuple, list etc
Example:
a = 10
b = ’its a string refered by variable b’
ls = [10,20,30,45]
Points to remember:
1. the naming of variable is done according to identifier naming rules
2. in python the variables are dynamically typed i.e. the data type of a variable is decided based on the data assigned to the variable
3. its all ways a good convention to name the variable meaningfully i.e according to its purpose in the program
ASSIGNMENT
References:
1. KVS student support material
3. https://realpython.com