Final Unit-Ii Python Programming
Final Unit-Ii Python Programming
UNIT II
Operators in Python : Arithmetic operators, Assignment operators, Comparison
operators, Logical operators, Identity operators, Membership operators, Bitwise
operators, Precedence of operators, Expressions.
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example print(10 + 5)
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
PYTHON PROGRAMMING I YEAR/I SEM MRCET
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Example:
Output:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Program
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('a=b:', a==b)
print('a+=b:', a+b)
print('a-=b:', a-b)
print('a*=b:', a*b)
print('a%=b:', a%b)
print('a**=b:', a**b)
print('a//=b:', a//b)
Output:
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
PYTHON PROGRAMMING I YEAR/I SEM MRCET
== Equal x == y
!= Not equal x != y
Program:
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)
Output:
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
PYTHON PROGRAMMING I YEAR/I SEM MRCET
Python Logical Operators
Logical operators are used to combine conditional statements:
and Returns True if both statements are true x < 5 and x < 10
Not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true
Program
a=5 # initialize the value of a
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))
Output:
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa: True
is not Returns True if both variables are not the same x is not y
object
Program:
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c=a
PYTHON PROGRAMMING I YEAR/I SEM MRCET
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
Output:
True
False
False
True
True
False
Program
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
Output:
Is value Present? True
Is value not Present? True
<< Zero fill left Shift left by pushing zeros in from the x << 2
shift right and let the leftmost bits fall off
Program
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)
Output:
a&b: 4
a|b: 7
a^b: 3
~a: -6
PYTHON PROGRAMMING I YEAR/I SEM MRCET
a<<b: 320
a>>b: 0
Precedence of Operators:
The operator precedence is used to define the operator's priority i.e. which operator will be executed first.
The operator precedence is similar to the BODMAS rule that we learned in mathematics. Refer to the list
specified below for operator precedence.
1. ()[]{} Parenthesis
2. ** Exponentiation
8. ^ Bitwise XOR
x = 12
y = 14
z = 16
result_1 = x + y * z
result_2 = (x + y) * z
result_3 = x + (y * z)
Output :
Example 1:
>>>
3+4*2
11
>>> (10+10)*2 40
Example 2:
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)
PYTHON PROGRAMMING I YEAR/I SEM MRCET
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)
Output:
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Expressions in Python:
An expression is a combination of operators and operands that is interpreted to produce some other
value.
An example of expression can be : x=x+10. In this expression, the first 10 is added to the variable x. After
the addition is performed, the result is assigned to the variable x.
Example :
x = 25 # a statement
x = x + 10 # an expression
print(x)
Output :
35
In any programming language, an expression is evaluated as per the precedence of its operators.
So that if there is more than one operator in an expression, their precedence decides which
operation will be performed first.
We have many different types of expressions in Python.
1.Constant Expressions:
These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
2. Arithmetic Expressions:
The operators used in these expressions are arithmetic operators like addition, subtraction, etc.
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
Example:
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions:
These are the kind of expressions that produce only integer results after all computations and type
conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
PYTHON PROGRAMMING I YEAR/I SEM MRCET
Output
25
4. Floating Expressions:
These are the kind of expressions which produce floating point numbers as result after all
computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output
2.6
5. Relational Expressions:
In these types of expressions, arithmetic expressions are written on both sides of relational operator
(> , < , >= , <=).
Those arithmetic expressions are evaluated first, and then compared as per relational operator and
produce a boolean output in the end.
These expressions are also called Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions:
These are kinds of expressions that result in either True or False. It basically specifies one or more
conditions.
And P and Q It returns true if both P and Q are true otherwise returns false
Example:
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
PYTHON PROGRAMMING I YEAR/I SEM MRCET
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions:
These are the kind of expressions in which computations are performed at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
8. Combinational Expressions:
We can also use different types of expressions in a single expression, and that will be termed as
combinational expressions.
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
9.Conditional expression:
Syntax: true_value if condition else false_value
>>> x = “1” if True else “2”
>>> x
>>> ‘1’
PYTHON PROGRAMMING I YEAR/I SEM MRCET
CONTROL FLOW AND LOOPS
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Python’s default indentation spaces are four spaces. The number of spaces, however, is
entirely up to the user. However, a minimum of one space is required to indent a
statement.
To indent in Python, whitespaces are preferred over tabs. Also, use either whitespace
or tabs to indent; mixing tabs and whitespaces in indentation can result in incorrect
indentation errors.
Example:
if 5 > 2:
print("Five is greater than two!")
Output: Five is greater than two!
Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Conditional Statements in Python:
Python if Statement: (Conditional)
An if statement executes a block of code only when the specified condition is met.
Syntax:
PYTHON PROGRAMMING I YEAR/I SEM MRCET
if condition:
# body of if statement
If condition evaluates to True, the body of the if statement is executed.
If condition evaluates to False, the body of the if statement will be skipped from
execution.
Ex:
x=3
y = 10
if x < y:
print("x is smaller than y.")
Output: x is smaller than y.
Flow Chart:
Ex:
x=3
PYTHON PROGRAMMING I YEAR/I SEM MRCET
y=3
if x < y:
print("x is smaller than y.")
elif x == y:
print("x is equal to y.")
else:
print("x is greater than y.")
Ex-2:
Nested if Statement:
Python supports nested if statements which means we can use a conditional if and if...else
statement inside an existing if statement.
There may be a situation when you want to check for additional conditions after the initial
one resolves to true. In such a situation, you can use the nested if construct.
Syntax
if boolean_expression1:
statement(s)
if boolean_expression2:
statement(s)
Flowchart of Nested if Statement
Following is the flowchart of Python nested if statement −
if num % 2 == 0:
if num % 3 == 0:
print("....execution ends....")
output:
num = 36
Divisible by 3 and 2
....execution ends....
Loops in Python
Python loops allow us to execute a statement or group of statements multiple times.
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
There may be a situation when you need to execute a block of code several number of times.
Flowchart of a Loop
PYTHON PROGRAMMING I YEAR/I SEM MRCET
Types of Loops in Python
Python programming language provides following types of loops to handle looping requirements.
1.While Loop
2.For Loop
3.Nested For Loop
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.
Flowchart
The code prints “Hello” three times using a ‘while' loop and then, after the loop, it prints “In Else
Block” because there is an “else” block associated with the ‘while' loop.
Example:
count = 0
while (count < 3):
count = count + 1
print("Hello")
else:
print("In Else Block")
Output
Hello
Hello
Hello
In Else Block
2.For Loop:
The For Loops in Python are a special type of loop statement that is used for sequential traversal.
Python For loop is used for iterating over an iterable like a String, Tuple, List, Set, or Dictionary.
Example1:
Example:
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
PYTHON PROGRAMMING I YEAR/I SEM MRCET
Output:
0
1
2
3
4
5
Finally finished
Output:
b
a
n
a
n
a
In the following example, the for loop traverses a tuple containing integers and returns the total of all
numbers.
PYTHON PROGRAMMING I YEAR/I SEM MRCET
Python for Loop with Lists
Python's list object is also an indexed sequence, and hence you can iterate over its items using a for
loop.
Example
In the following example, the for loop traverses a list containing integers and prints only those which
are divisible by 2.
Where,
In this example, we will see the use of range with for loop.
Output:
0
1
PYTHON PROGRAMMING I YEAR/I SEM MRCET
2
3
4
5
range(start,stop)
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter:
range(2, 6), which means values from 2 to 6 (but not including 6):
Example:
Using the start parameter:
Output:
2
3
4
5
Range(start,stop,next)
The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
Running a simple for loop over the dictionary object traverses the keys used in it.
Example:
for i in range(1, 7):
for j in range(i):
print(i, end=' ')
print()
Output:
1
22
333
4444
55555
6 6 6 6 6 6
PYTHON PROGRAMMING I YEAR/I SEM MRCET
Example 2 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(5,i-1,-1):
print('')
Output:
11111
2222
333
44
n=5
print()
output:
**
***
****
*****
n=5
print()
output:
*****
****
***
**
n=5
ouput:
***
*****
*******
*********
print(‘ ‘ * (n – i) + ‘*’ * (2 * i – 1)) prints spaces followed by stars. Spaces decrease and stars
increase per row to form the pyramid.
n=5
output:
PYTHON PROGRAMMING I YEAR/I SEM MRCET
*
***
*****
*******
*********
*******
*****
***
*
Python Loop Control Statements (or) Loop manipulation (or)
unconditional (or) jumping statements:
Loop control statements change execution from their normal sequence.
When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
1.break
2.continue
3.pass
1.break:
It is used to exit a while loop or a for a loop. It terminates the looping & transfers execution to the
statement next to the loop.
The break keyword is used to break out a for loop, or a while loop.
Syntax: break
Example :
End the loop if i is larger than 3:
for i in range(9):
if i ==3:
break
print(i)
Output:
0
1
2
2.Continue:
With the continue statement we can stop the current iteration of the loop, and continue with the next:
Syntax: continue
PYTHON PROGRAMMING I YEAR/I SEM MRCET
Example:
for i in range(9):
if i ==3:
continue
print(i,end=" ")
output:
01245678
for x in range(10):
#check whether x is even
if x % 2 == 0:
continue
print (x)
Output:
1
3
5
7
9
3.The pass Statement
for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.
Syntax:
pass
Example:
for x in [0, 1, 2]:
pass
# having an empty for loop like this, would raise an error without the pass statement