Python_Unit_II_SPN_2023
Python_Unit_II_SPN_2023
Narote
Unit II :
Flow Statements
By
Dr. Sandipann P Narote
Head (E & TC)
Contents
Basic operators :
• Arithmetic, comparison, relational, assignment, logical, bitwise, etc…
Python Program Flow Control Conditional blocks
• Conditional Statements(if, if else,…. nested if).
• Simple for loops in python, For loop using ranges, string, list and dictionaries.
• Use of while loops in python, Loop manipulation using pass, continue, break
and else.
Programming using Python conditional and loop blocks.
Learning Outcomes
Operators in Python
The operator can be defined as a symbol which is responsible for a
particular operation between two operands.
Python operators are used to manipulate values.
Python provides a variety of operators described as follows.
Arithmetic GPP = 4 + 5
Membership
Assignment
Operators in Identity
Python
Comparison
Logical
Bitwise
Arithmetic Operator
Addition
+
Floor Division - Subtraction
//
Operators
Exponent ** / Division
% Reminder
Multiplication *
Comparison Operator
Comparison Operator
Always return a Boolean result
• True or False a >= b
• Indicates whether a relationship holds
between their operands
Operands
Greater than or
== Equal to equal <=
Greater than or
!= Not Equal to Comparison
equal >=
Comparison Operator
Examples
6 != 6 evaluates to False
Comparison Operator
# equal to operator
a=5 print('a == b =', a == b)
b=2 # not equal to operator a == b = False
print('a != b =', a != b) a != b = True
# greater than operator a > b = True
print('a > b =', a > b) a < b = False
# less than operator
print('a < b =', a < b)
Assignment Operators
Assignment
-= (Assignment after Sub) **= (Assignment after Expt)
Assignment Operators
Add and equal operator (+=)
a=5
Sub and equal operator (+=)
b=10
a+=b a=5
Mul and equal operator (*=)
print(a) b=10
a-=b a=5 Div and equal operator (/=)
print(a) b=10
#Output a*=b a=6
-5 print(a) b=4
#Output a/=b
50 print(a)
#Output
1.5
Assignment Operators
Floor Div & equal operator (//=) Modulus & equal operator (%=)
This operator (//=) is used to do This operator (%=) is used to get the
the floor division of the left operand remainder by dividing the operand on
by the right-side operand and then the left side by the right-hand side
assign the value to the left operand operand and then assigning the value
of the remainder to the left operand
a=6 a=6
b=4 b=4
a//=b a//=b
print(a) print(a)
#Output #Output
1 2
Bitwise Operators
Binary AND Sets each bit to 1 if both bits are 1.
Negation
Logical Operators
and (logical and) Returns True if both statements are true.
Logical Operators
Value of a Value of b Value of GPP
GPP = a or b
True True True
a = True Output True False True
b = False
# Logical or
a or b = True False True True
GPP = not a
a = True Output
Value of a Value of GPP b = False not a = False
# Logical not not b = true
True False
print(“ not a =", not a)
False True print(“ not b =", not b)
Identity Operators
is
01
a is b
is not
02
a is not b
Membership Operators
in
01
a in b
not in
02
a is not in b
01 Sequence
Conditional or Selection 02
03 Iteration or Looping
Transfer or Jumping 04
Sequence
Sequence Program
1. for
1. if 1. Break
2. while
2. If-else 2. Continue
3. If-elif-else 3. pass
4. Nested if else
If Statement : Python
If Statement : Python
If Statement
The execution encounters the if condition and acts accordingly.
If it is true, it executes the body and if it is false, it exits
the if statement. Example:
>>> a = 30 a = 55
>>> b = 40 b = 100
>>> if a < b : if b > a:
>>> print(" b is greater") print ("b is greater than a")
• When it reaches the if statement it checks whether the value of b is
greater or not.
• If b is greater, it prints “b is greater“.
• Now if the condition is false, it exits the if statement and executes the
next statement. In order to print the next statement, we can add a
keyword ‘else’ for the alternate result that we wish to execute.
If Else
If-else statement:
Theif-else statement provides an else block combined with the if statement
which is executed in the false case of the condition.
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Example:
age = int(input("Enter your age : ")) Output:
if age>=18: Enter your age: 19
print("You are eligible to vote !!") You are eligible to vote!!
else:
print("Sorry! you have to wait !!"))
If Else
if expression
Statement
else
Statement
If ….. else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
positive or Zero
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
If ….. else
>>> a = 30
>>> b = 40
num =input(("Enter number: "))
>>> if a < b :
if num % 2 == 0:
>>> print(" b is greater")
print("Even")
>>> else:
else:
>>> print(" a is greater")
print("Odd")
If else
# If else
x,y =2,8
if(x < y):
b = "x is less than y"
print(b)
If else
Error # If else
# If else
Condition is not x,y =9,5
x,y =9,5
satisfied if(x < y):
if(x < y):
b = "x is less than y" b = "x is less than y“
print(b) else:
b= "x is greater than y"
• Define two variables x, y = 9, 5 print(b)
If-elif-else statement
The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them.
Syntax:
if condition1:
False
# block of statements Condition ? Statement 1 Statement 2
elif condition2:
Main True
# block of statements Body
Statement 1
elif condition3:
# block of statements else
Statement 2 body
else:
# block of statements
If else
: Colon Must
if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple,
a dictionary, a set, or a string).
for loop we can execute a set of statements, once for each item in a list,
tuple, set etc
For Loop
# Print numbers from 1 to 5
for i in range(5): Range Function
print(i) Body of the for loop
For loop
# Print numbers
numbers= [1,2, 3, 4,5]
for number in numbers
print(i)
Output
1
2
3 Output
4
5
For Loops
word="anaconda"
for letter in word:
print (letter)
Output
a
n
a
c
o
n
d
a
Output
Apple
Banana
Car
Dolphin
Output
Sum of numbers is 10
range (a)
range(a,b)
range(a,b,c)
0
1
2
2
3
4
5
2
7
12
17
# Output
Printing with step: 1
Printing with step: 4
Printing with step: 7
Python allows us to use the else statement with the for loop which can be executed
only when all the iterations are exhausted.
Here, we must notice that if the loop contains any of the break statement then the
else statement will not be executed.
Example:
for i in range(1,5):
print(i,end=' ')
else:
print("for loop completely exhausted");
Output:
1234
for loop completely exhausted
Syntax of break
break
print("The end")
s
t
r
The end
print("The end")
s
t
r
n
g
The end
Iteration or Looping
While Loop
While loop (iterations)
While loop will repeat execution of one or more lines of code, until the
boolean condition is satisfied/changes.
The code block inside the while loop will execute as long as the boolean
condition in the while loop is True.
Example: Output:
i=1; 1
while i<=3:
2
print(i);
i=i+1; 3
While Loop
# While loop syntax
while (condition):
statement
A while loop will always first check the condition before running
If the condition is True, the loops body is executed.
While it stays True, it keeps repeating.
If the condition becomes False, it ends the loop.
Example
# Python program to illustrate Output
# while loop Hello GPP
count = 0 Hello GPP
# define while loop Hello GPP
while (count < 5): Hello GPP
count = count + 1 Hello GPP
print("Hello GPP")
• While statement in python also supports else statement in association with it. The else
statement is optional.
• The else statement written after the while statement will be executed when the expression of
while returns False.
• So, else statement will be executed once the execution of the while is completed normally( By
expression returning False).
• If a break statement is executed inside the while loop and the execution is stopped, then else
block is skipped, and control jumps directly to the statement below the while..else.
Example: Output:
i=1; 1
while i<=3: 2
print(i); 3
i=i+1; while loop terminated
else:
print("while loop termina
ted")
False False
Expression
Expression
of loop
of loop
True True
Yes
Yes Continue
Break
No No
Exit loop Exit loop
Remaining part
Remaining part
of loop
of loop
False
Expression
of loop
True
Yes
Continue
No
Exit loop
Remaining part
of loop
False
Expression
of loop
True
Yes
Break
No
Exit loop
Remaining part
of loop
Break
n=5 4
while n > 0: 3
n -= 1 Loop ended
if n == 2:
break
print(n)
print('Loop ended')
Key Takeaways
When you already know the number of When you don’t know the number of
Use Case
iterations iteration.
Every element is explicitly
Every element is fetched through the
Iteration incremented or decremented by the
iterator/generator. Example, range()
user
For loop can be iterated on generators in While loop cannot be iterated on
Generator Support
Python. Generators directly.
While loop with incrementing
For loop with range() uses 3 operations. range() variable uses 10 operations. i+=1 is
Disassembly
function is implemented in C, so, its faster. interpreted, hence, it’s slower than
range()
Speed (May Vary on On basis of disassembly, for loop is faster than On basis of disassembly, the while
Conditions) while loop. loop is slower than for loop.
row_num = 3
col_num = 4
multi_list = [[0 for col in range(col_num)] for row in
range(row_num)]
for row in range(row_num):
for col in range(col_num):
multi_list[row][col]= row*col
print(multi_list)
Thank You