Unit II PYTHON OPERATORS AND CONTROL FLOW STATEMENTS
Unit II PYTHON OPERATORS AND CONTROL FLOW STATEMENTS
UNIT II
PYTHON OPERATORS AND CONTROL FLOW STATEMENTS
(10 Marks)
Unit Outcomes
h
2a. Write simple Python program for the given arithmetic expressions.
ik
ha
2b. Use different types of operators for writing the arithmetic expressions.
2c. Write a 'Python' program using decision making structure for two-way
.S
branching to solve the given problem.
2d. Write a Python' program using decision making structure for multi-way
.A
1
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Python Operators
o The operator can be defined as a symbol which is responsible for a particular
operation between two operands.
o Operators are the pillars of a program on which the logic is built in a particular
programming language.
o Python provides a variety of operators described as follows.
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
h
Bitwise Operators
ik
Membership Operators
ha
Identity Operators
.S
Arithmetic operators
.A
.A
of
Pr
2
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
(divide) operand by the second operand. Notice that >>> b=10
ik
division results in a floating-point value. >>> a/b
ha
2.0
* It is used to multiply one operand with the other. >>> a=20
.S
(Multiplication) >>> b=10
>>> a*b
.A
200
% It returns the reminder after dividing the first >>> a=20
.A
0
Pr
3
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Comparison operator
o Comparison operators are used to comparing the value of the two operands and
returns boolean true or false accordingly.
h
ik
o The comparison operators are described in the following table.
Operator Description Example
==
ha
If the value of two operands is equal, then the >>> a=30
condition becomes true. >>> b=20
.S
>>> a==b
False
.A
!= If the value of two operands is not equal then the >>> a=30
condition becomes true. >>> b=20
>>> a!=b
.A
True
<= If the first operand is less than or equal to the >>> a=30
of
False
>= If the first operand is greater than or equal to the >>> a=30
second operand, then the condition becomes true. >>> b=20
>>> a>=b
True
> If the first operand is greater than the second >>> a=30
operand, then the condition becomes true. >>> b=20
>>> a>b
True
< If the first operand is less than the second >>> a=30
operand, then the condition becomes true. >>> b=20
>>> a<b
False
4
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
o The assignment operators are used to assign the value of the right expression to the
h
left operand.
ik
o The assignment operators are described in the following table.
ha
Operator Description Example
= It assigns the value of the right expression to the >>> a=30
.S
left operand. >>> a
30
.A
30
Pr
5
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
//= A//=b will be equal to a = a// b >>> a=4
ik
>>> b=3
ha
>>> a//=b
>>> print(a)
.S
1
.A
.A
of
Pr
6
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Bitwise operator
o The bitwise operators perform bit by bit operation on the values of the two operands.
h
ik
ha
.S
For example,
.A
(binary and) Here, binary for 2 is 10, and that for 3 is 11. &-ing them >>> b=3
results in 10, which is binary for 2. >>> bin(a)
of
'0b10'
Pr
>>> bin(3)
'0b11'
>>> a&b
2
| It performs bit by bit OR on the two values. Here, OR- >>> a=2
(binary or) ing 10(2) and 11(3) results in 11(3). >>> b=3
>>> bin(a)
'0b10'
>>> bin(3)
'0b11'
7
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
>>> a|b
3
^ It performs bit by bit XOR(exclusive-OR) on the two >>> a=2
(binary xor) values. Here, XOR-ing 10(2) and 11(3) results in 01(1). >>> b=3
>>> bin(a)
'0b10'
>>> bin(3)
'0b11'
>>> a^b
1
h
~ It returns the one’s complement of a number’s binary. It >>> a=2
ik
(negation) flips the bits. Binary for 2 is 00000010. Its one’s >>> b=3
ha
complement is 11111101. This is binary for -3. So, this >>> bin(a)
results in -3. '0b10'
.S
>>> ~a
-3
.A
<< It shifts the value of the left operand the number of >>> a=2
(left shift) places to the left that the right operand specifies. Here, >>> bin(a)
.A
8
Pr
>> It shifts the value of the left operand the number of >>> a=2
(right shift) places to the right that the right operand specifies. Here, >>> bin(a)
binary of 2 is 01. 3>>2 shifts it two places to the right. '0b10'
This results in 00, which is binary for 0. >>> a>>2
0
8
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Logical Operators
h
ik
o The logical operators are used primarily in the expression evaluation to make a
ha
decision. Python supports the following logical operators.
Operator Description Example
.S
and If both the expression are true, then the >>> a=2
condition will be true. If a and b are the two >>> b=3
.A
9
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Membership Operators
o These operators test whether a value is a member of a sequence.
o The sequence may be a list, a string, or a tuple.
o We have two membership python operators- ‘in’ and ‘not in’.
Operator Description Example
in This checks if a value is a member of a >>> pets=["dog","cat","rat"]
sequence. In our example, we see that the string >>> "fox" in pets
‘fox’ does not belong to the list pets. But the False
string ‘cat’ belongs to it, so it returns True. >>> "cat" in pets
True
h
not in Unlike ‘in’, ‘not in’ checks if a value is not a >>> pets=["dog","cat","rat"]
ik
member of a sequence. >>> "fox" not in pets
ha
True
>>> "cat" not in pets
.S
False
.A
Identity Operators
o These operators test if the two operands share an identity.
.A
10
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Operator Precedence
o The precedence of the operators is important to find out since it enables us to know
which operator should be evaluated first.
o The precedence table of the operators in python is given below.
Operator Description
** The exponent operator is given priority over all the others used
in the expression.
~+- The negation, unary plus and minus.
* / % // The multiplication, divide, modules, reminder, and floor
division.
h
+- Binary plus and minus
ik
>> << Left shift and right shift
ha
& Binary and.
^| Binary xor and or
.S
<= < > >= Comparison operators (less then, less then equal to, greater
then, greater then equal to).
.A
+=
of
*= **=
is is not Identity operators
Pr
11
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
ik
ha
o Sometimes, in a program, we may want to make a decision based on a condition.
o We know that an expression’s value can be True or False.
.S
o We may want to do something only when a certain condition is true.
o For example, assume variables a and b. If a is greater, then we want to print “a is
.A
Python if Statements
Pr
if expression:
statement(s)
12
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
Example 1
ik
num = int(input("enter the number?"))
ha
if num%2 == 0:
print("Number is even")
.S
Output:
.A
a = int(input("Enter a? "));
Pr
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");
Output:
Enter a? 100
13
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Enter b? 120
Enter c? 130
c is largest
h
ik
ha
.S
.A
.A
of
Pr
if condition:
#block of statements
else:
#another block of statements (else-block)
14
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
Example 2: Program to check whether a number is even or not.
ik
num = int(input("enter the number?"))
ha
if num%2 == 0:
print("Number is even...")
.S
else:
print("Number is odd...")
.A
Output:
enter the number?10
.A
Number is even
of
o The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them.
o We can have any number of elif statements in our program depending upon our need.
However, using elif is optional.
o The elif statement works like an if-else-if ladder statement in C. It must be succeeded
by an if statement.
o The syntax of the elif statement is given below.
15
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
h
ik
ha
.S
.A
.A
of
Pr
Example 1
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
16
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
if marks > 85 and marks <= 100:
ik
print("Congrats ! you scored grade A ...")
ha
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
.S
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
.A
else:
print("Sorry you are fail ?")
of
Output
Pr
17
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
Python Loop
o When we want some statements to execute a hundred times, you don’t repeat them
100 times.
o Think of when we want to print numbers 1 to 99. Or that we want to say Hello to 99
friends. In such a case, we can use loops in python.
o Here, we will discuss 4 types of Python Loop:
Python For Loop
Python While Loop
Python Loop Control Statements
Nested For Loop in Python
h
While Loop
ik
A while loop in python iterates till its condition becomes False.
ha
In other words, it executes the statements under itself while the condition it takes is True.
When the program control reaches the while loop, the condition is checked.
.S
If the condition is true, the block of code under it is executed.
.A
This continues until the condition becomes false. Then, the first statement, if any, after
the loop is executed.
of
>>> a=3
Pr
>>> while(a>0):
print(a)
a-=1
3
2
1
This loop prints numbers from 3 to 1. In Python, a—wouldn’t work. We use a-=1 for the
same.
18
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
a. An Infinite Loop
Be careful while using a while loop.
h
Because if you forget to increment the counter variable in python, or write flawed
ik
logic, the condition may never become false.
ha
In such a case, the loop will run infinitely, and the conditions after the loop will
.S
starve.
To stop execution, press Ctrl+C.
.A
When the condition becomes false, the block under the else statement is executed.
Pr
>>> a=3
>>> while(a>0):
print(a)
a-=1
else:
print("Reached 0")
19
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
3
2
1
Reached 0
In the following code, we put a break statement in the body of the while loop for a==1.
So, when that happens, the statement in the else block is not executed.
>>> a=3
>>> while(a>0):
print(a)
a-=1
h
if a==1: break;
ik
else:
print("Reached 0")
ha
.S
3
2
.A
one line.
>>> a=3
of
3
2
1
We can see that there were two statements in while’s body, but we used semicolons to
separate them. Without the second statement, it would form an infinite loop.
20
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
For Loop
Python for loop can iterate over a sequence of items.
The structure of a for loop in Python is different than that in C++ or Java.
That is, for(int i=0;i<n;i++) won’t work here.
In Python, we use the ‘in’ keyword.
Lets see a Python for loop Example
0
1
h
ik
2
ha
If we wanted to print 1 to 3, we could write the following code.
1
2
.A
3
of
Pr
21
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
We use the list function to convert the range object into a list object.
Calling it with two arguments creates a sequence of numbers from the first to the
second.
>>> list(range(2,7))
h
[2, 3, 4, 5, 6]
ik
We can also pass three arguments. The third argument is the interval.
ha
>>> list(range(2,12,2))
.S
[2, 4, 6, 8, 10]
Remember, the interval can also be negative.
.A
>>> list(range(12,2,-2))
[12, 10, 8, 6, 4]
.A
>>> list(range(12,2))
Pr
[]
>>> list(range(2,12,-2))
[]
>>> list(range(12,2,2))
[]
22
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
1
2
3
>>> for i in {2,3,3,4}:
print(i)
2
3
4
h
>>> for i in 'wisdom':
ik
print(i)
ha
w
i
.S
s
d
.A
o
m
.A
>>> list=['Romanian','Spanish','Gujarati']
>>> for i in range(len(list)):
print(list[i])
Romanian
Spanish
Gujarati
23
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
3
ik
4
ha
5
6
.S
7
8
.A
9
Reached else
.A
Like in the while loop, it doesn’t execute if you break out of the loop or if an exception is
of
raised.
Pr
24
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
*
ik
**
ha
**
***
.S
****
Let’s look at some nested while loops to print the same pattern.
.A
>>> i=6
>>> while(i>0):
.A
j=6
while(j>i):
of
print("*",end=' ')
Pr
j-=1
i-=1
print()
*
**
***
****
*****
25
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
h
ik
a. break statement
ha
When we put a break statement in the body of a loop, the loop stops executing, and
control shifts to the first statement outside it.
.S
We can put it in a for or while loop.
.A
if i=='a': break;
b
of
r
Pr
e
a
b. continue statement
When the program control reaches the continue statement, it skips the statements after
‘continue’.
It then shifts to the next item in the sequence and executes the block of code for it.
We can use it with both for and while loops.
>>> i=0
>>> while(i<8):
26
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
i+=1
if(i==6): continue
print(i)
1
2
3
4
5
7
8
h
If here, the iteration i+=1 succeeds the if condition, it prints to 5 and gets stuck in an
ik
infinite loop. You can break out of an infinite loop by pressing Ctrl+C.
ha
>>> i=0
>>> while(i<8):
.S
if(i==6): continue
print(i)
.A
i+=1
0
.A
1
2
of
3
Pr
4
5
c. pass statement
In Python, we use the pass statement to implement stubs.
When we need a particular loop, class, or function in our program, but don’t know what
goes in it, we place the pass statement in it.
It is a null statement.
The interpreter does not ignore it, but it performs a no-operation (NOP).
>>> for i in 'selfhelp':
27
Padmashri Dr. Vitthalrao Vikhe Patil Institute Of Technology Engineering (Polytechnic ), Pravaranagar
PWP-22616,CM
pass
>>> print(i)
p
To run this code, save it in a .py file, and press F5. It causes a syntax error in the shell.
h
ik
ha
.S
.A
.A
of
Pr
28