Python unit 2
Python unit 2
1 BASIC OPERATOR
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
1. Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
*
Multiplies values on either side of the operator a * b = 200
Multiplication
Floor Division - The division of operands where the result is the 9//2 = 4 and
quotient in which the digits after the decimal point are removed. 9.0//2.0 = 4.0,
//
But if one of the operands is negative, the result is floored, i.e., -11//3 = -4,
rounded away from zero (towards negative infinity) -11.0//3 = -4.0
Example
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c=a-b
print ("Line 2 - Value of c is ", c)
c=a*b
print ("Line 3 - Value of c is ", c)
c=a/b
print ("Line 4 - Value of c is ", c)
c=a%b
print ("Line 5 - Value of c is ", c)
a=2
b=3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b=5
c = a//b
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2.1
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
2. Comparison Operators
These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Example
Assume variable a holds 10 and variable b holds 20, then –
a = 21
b = 10
c=0
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")
if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")
if ( a < b ):
print ("Line 3 - a is less than b")
else:
print ("Line 3 - a is not less than b")
if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")
a = 5;
b = 20;
if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")
if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")
When you execute the above program it produces the following result –
+= Add AND It adds right operand to the left operand and assign the c += a is equivalent
result to left operand to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign c - = a is equivalent
the result to left operand to c = c - a
*= Multiply AND It multiplies right operand with the left operand and c *= a is equivalent to
assign the result to left operand c=c*a
/= Divide AND It divides left operand with the right operand and assign c /= a is equivalent
the result to left operand to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result c %= a is equivalent
to left operand to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators c **= a is equivalent
and assign value to the left operand to c = c ** a
//= Floor Division It performs floor division on operators and assign value to c //= a is equivalent
the left operand to c = c // a
Example
Assume variable a holds 10 and variable b holds 20, then –
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )
c *= a
print ("Line 3 - Value of c is ", c )
c /= a
print ("Line 4 - Value of c is ", c )
c =2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
4. Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in
the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out
the bitwise operators supported by Python language with an example each in those, we use the above
two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100 ( 12 )
a|b = 0011 1101 ( 61 )
a^b = 0011 0001 (49 )
~a = 1100 0011 (-61)
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0
Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a | b; # 61 = 0011 1101
print ("Line 2 - Value of c is ", c)
c = a ^ b; # 49 = 0011 0001
print ("Line 3 - Value of c is ", c)
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
5. Logical Operators
Logical operators perform Logical AND, Logical OR and Logical NOT operations.
and Logical AND: True if both the operands are true x and y
Example
a = True
b = False
print("a and b is", a and b)
print("a or b is", a or b)
print("not a is", not a )
Output:
a and b is False
a or b is True
not a is False
6. Python Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below −
x in y, here in results in a
Evaluates to true if it finds a variable in the specified
In 1 if x is a member of
sequence and false otherwise.
sequence y.
Example
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("a is available in the given list")
else:
print ("a is not available in the given list")
if ( b not in list ):
print ("b is not available in the given list")
else:
print ("b is available in the given list")
a=2
if ( a in list ):
print ("a is available in the given list")
else:
print ("a is not available in the given list")
output:
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −
Evaluates to true if the variables on either side of the operator x is y, here is results in
Is
point to the same object and false otherwise. 1 if id(x) equals id(y).
x is not y, here is
Evaluates to false if the variables on either side of the operator
is not not results in 1 if id(x)
point to the same object and true otherwise.
is not equal to id(y).
Example
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True because x is
equal to y
print(x is not z)
print(x is not y)
print(x != y)
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
Sr. No. Operator & Description
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
9 == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Operator precedence affects how an expression is evaluated.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than
+, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom.
Example
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
When you execute the above program, it produces the following result –
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
2.2 CONTROL FLOW STATEMENTS
A control flow statement is a block of programming that analyses variables and chooses a direction in
which to go based on given parameters. It determines the order in which the program’s code executes.
They are decision Making Statements that allow the program to take the decision as which statement
should be executed next.
Decision Making statements are used when we want a set of instructions should be executed in one
situation and different instructions should be executed in another situation .Decision making can be
implemented in python using:
Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in python are:
if statement
if..else statements
nested if statements
if-elif ladder
1. if statement
if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e. if a certain condition is true then a block of
statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if condition is true
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the
value is true then it will execute the block of statements below it otherwise not.
We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be
identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block will consider only statement1 to be inside its block.
Flowchart:-
Output:
i is greater than 5
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is not executed.
2. if- else
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if, we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code when the
condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is
false after call the statement which is not in block (without spaces).
3. nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements means an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements.
i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Here, a user can decide among multiple options. The if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Example:-
number = 0
Output:
a is greater
Example 2:
a=10
b=100
print("a is gretaer than b ") if (a>b) else print("a is less than b ") if (a<b) else print("Zero");
B] LOOPING IN PYTHON
1. while loop
A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method of
grouping statements.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example
i=1
while (i <=10):
print ("The count is:", i)
i=i+1
print ("Out of While Loop")
2. for loop
In Python, the for loop is used to run a block of code for a certain number of times. It is used to iterate
over any sequences such as list, tuple, string, etc.
Syntax
for iterating_var in sequence:
statements(s)
Example 1:
Output:
Python
PHP
MAD
ETI
MAN
Example 2:
square = 1
numbers_list = [1,2,3,4,5,6,7]
for i in numbers_list:
square = i*i
print("The square of", i, "is", square)
Output:
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
In the above example, we are calculating the squares of all elements present in the list of numbers that
we have created, named ‘numbers_list’, using a Python for loop.
The variable i iterates from the beginning to the end of the Python List, and when the program enters
the body of the loop, the square of each element is calculated using the variable i and stored in a
variable named ‘square’.
range( )
The range( ) type returns an immutable sequence of numbers between the given start integer to the
stop integer.
range() constructor has two forms of definition:
1. range(stop)
2. range(start, stop[, step])
range ( ) Parameters
range() takes mainly three arguments having the same use in both definitions:
start - integer starting from which the sequence of integers is to be returned. Default is 0.
stop - integer before which the sequence of integers is to be returned.
The range of integers end at stop - 1.
step (Optional) - integer value which determines the increment between each integer in the
sequence. Default is 1
Example 1:
#Create a sequence of numbers from 3 to 5, and print each item in the sequence:
seq = range(3, 6)
for n in seq:
print(n)
Or
for i in range(3,6):
print(i)
Output:
3
4
5
Example 2:
Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:
Output:
3
5
7
9
11
13
15
17
19
Example 4: Create a list of even number between the given numbers using range()
start = 2
stop = 14
step = 2
print(list(range(start, stop, step)))
Output:
[2, 4, 6, 8, 10, 12]
Example 5: How range() works with negative step?
start = 2
stop = -14
step = -2
print(list(range(start, stop, step)))
print(list(range(start, 14, step))) # value constraint not met
output:
[2, 0, -2, -4, -6, -8, -10, -12]
[]
3. Nested Loops:
Python programming language allows to use one loop inside another loop.
Following section shows few examples to illustrate the concept.
Syntax:
A final note on loop nesting is that we can put any type of loop inside of any other type of loop.
For example a for loop can be inside a while loop or vice versa.
Example1:
sem1 = ["CSS", "OSY", "STE"]
sem2 = ["PHP", "PWP", "MAD"]
for x in sem1:
for y in sem2:
print(x, y)
Output:
CSS PHP
CSS PWP
CSS MAD
OSY PHP
OSY PWP
OSY MAD
STE PHP
STE PWP
STE MAD
Python end parameter in print()
By default Python‘s print() function ends with a newline. A programmer with C/C++ background may
wonder how to print without a newline. Python’s print() function comes with a parameter called ‘end‘.
By default, the value of this parameter is ‘\n’, i.e. the new line character.
Example 1:
Here, we can end a print statement with any character/string using this parameter.
Output:
Welcome to Arrow
Output:
Welcome to@Arrow
Output:
1
22
333
4444
2.3 LOOP MANIPULATION STATEMENTS
1. break statement
The break statement terminates the loop containing it. Control of the program flows to the statement
immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
Syntax of break
break
The working of break statement in for loop and while loop is shown below.
Flowchart of break
Example 1: Python break
Output
s
t
r
The end
In this program, we iterate through the "string" sequence. We check if the letter is "i", upon which we
break from the loop. Hence, we see in our output that all the letters up till "i" gets printed. After that,
the loop terminates.
Example 2:
Output:
2
3
4
5
2. continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
Loop does not terminate but continues on with the next
iteration.
Syntax of Continue
continue
Output
s
t
r
n
g
The end
This program is same as the above example except the break statement has been replaced with
continue. We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we
see in our output that all the letters except "i" gets printed.
Example 2:
number_list = [2,3,4,5,6,7,8]
for i in number_list:
if i == 5:
continue
print(i)
Output:
2
3
4
6
7
8
3. pass statement
In Python programming, the pass statement is a null statement which can be used as a placeholder for
future code.
Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the
future. In such cases, we can use the pass statement.
When the pass statement is executed, nothing happens, but you avoid getting an error when empty
code is not allowed.
Syntax:
pass
Example:
Output:
Current character: P
Current character: y
Current character: t
Current character: h
Current character: o
Current character: n
In the above example, when the value of char becomes equal to ‘h’, the pass statement did nothing and
hence the letter ‘h’ is also printed
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that
does nothing. It only works as a dummy statement.
def fun():
pass
Difference between continue and pass
Consider the below example for better understanding the difference between continue and pass
statement.
Example:
s = "Arrow"
# Pass statement
for i in s:
if i == 'r':
print('Pass executed')
pass
print(i)
print() # for blank line
# Continue statement
for i in s:
if i == 'r':
print('Continue executed')
continue
print(i)
For loop in Python can have an optional else block. The else block will be executed only when all
iterations are completed. When break is used in for loop to terminate the loop before all the iterations
are completed, the else block is ignored.
Example:
for i in range(1,6):
print(i)
else:
print(" All iterations completed")
Output:
1
2
3
4
5
All iterations completed
Example 2: Else block is NOT executed in below Python program:
Output :
Such type of else is useful only if there is an if condition present inside the loop which somehow
depends on the loop variable.
In the following example, the else statement will only be executed if no element of the array is even, i.e.
if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in
the third iteration of the loop and hence the else present after the for loop is ignored. In the case of
array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed
Example
l=[1, 9, 8]
for ele in l:
if ele % 2 == 0:
print ("list contains an even number")
break
# This else executes only if break is NEVER
# reached and loop terminated after all iterations.
else:
print ("list does not contain an even number")