0% found this document useful (0 votes)
7 views

Python_Unit_II_SPN_2023

Uploaded by

rautsneha4500
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python_Unit_II_SPN_2023

Uploaded by

rautsneha4500
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Dr. S. P.

Narote

Python Programming (ET5106)

Unit II :
Flow Statements

By
Dr. Sandipann P Narote
Head (E & TC)

Government Polytechnic, Pune

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.

Government Polytechnic, Pune 1


Dr. S. P. Narote

Learning Outcomes

1. Write simple Python program to evaluate the given arithmetic


expression
2. Use different types of operators for writing arithmetic expressions.
3. Write a Python program using conditional statements for two way
branching to solve given problem.
4. Write a Python program using while loop for multiway branching to solve
the given problem.

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

Government Polytechnic, Pune 2


Dr. S. P. Narote

Arithmetic Operator
Addition
+
Floor Division - Subtraction
//

Operators

Exponent ** / Division

% Reminder
Multiplication *

# addition # floor division


a=7 print ('Sum: ', a + b) print ('Floor Division: ', a // b)
b=2 # subtraction # modulo
print ('Subtraction: ', a - b) print ('Modulo: ', a % b)
# multiplication # a to the power b
print ('Multiplication: ', a * b) print ('Power: ', a ** b)
# division
print ('Division: ', a / b)

Sum: 9 Floor Division:


Division 3
Subtraction: 5 Modulo 1
Modulo:
Multiplication: 14 Power: 49
Division: 3.5

Government Polytechnic, Pune 3


Dr. S. P. Narote

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 >=

< Less than Greater than >

Comparison Operator

 Examples

8 < 15 evaluates to True

6 != 6 evaluates to False

2.5 > 5.8 evaluates to False

4.0 == 4 evaluates to True

Government Polytechnic, Pune 4


Dr. S. P. Narote

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)

# greater than or equal to operator


print('a >= b =', a >= b) a >= b = True
# less than or equal to operator a <= b = False
print('a <= b =', a <= b)

Assignment Operators

= (Assigns to) /= (Assignment after Div)

+= (Assignment after Add) %= (Assignment after Mod)

Assignment
-= (Assignment after Sub) **= (Assignment after Expt)

*= (Assignment after Mult) //= (Assignment after floor div)

Government Polytechnic, Pune 5


Dr. S. P. Narote

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

Government Polytechnic, Pune 6


Dr. S. P. Narote

Bitwise Operators
Binary AND Sets each bit to 1 if both bits are 1.

& Sets each bit to 1 if one of the


bits is 1.

Right shift >> | Binary OR


Bitwise
Operators
Left shift << ^ Binary XOR
Sets each bit to 1 if only one
~ of the two bits is 1.

Negation

Logical Operators
and (logical and) Returns True if both statements are true.

Returns True if at least one statement is or (logical or)


true.
Reverses the result, returns False if the
Not (logical not) result is true.
Value of a Value of b Value of GPP
GPP = a and b
True True True
a = True Output True False False
b = False a and b = false False True False
# Logical and False False False
print(“a and b =", a and b)

Government Polytechnic, Pune 7


Dr. S. P. Narote

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

print(“a or b =", a or b) False False False

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

Operator Description Syntax


is True if the two operands refer to the same memory location x is y
True if the two operands do not refer to the same memory
is not x is not y
location

Government Polytechnic, Pune 8


Dr. S. P. Narote

Membership Operators

in
01
a in b

not in
02
a is not in b

Operator Description Syntax


in True if the value or variable is present in the sequence x in y
not in True if the value or variable is not present in the sequence x not in y

Types Of Control Structures


A Structured programming is an important feature of a programming
language which comprises following logical structure:

01 Sequence

Conditional or Selection 02

03 Iteration or Looping

Transfer or Jumping 04

Government Polytechnic, Pune 9


Dr. S. P. Narote

Sequence

Step by step execution


• Statement 1 Statement 1
• Statement 2
• Statement 3 Statement 2
• Statement 4
• ………………
Statement 3

Sequence Program

 Default control structure # Program for addition of numbers


X= 4
Y=6
Z=5
A= X+Y+Z
print(‘Sum is = ’,A)

Government Polytechnic, Pune 10


Dr. S. P. Narote

Flow Controls in Python

What are Loops in Python?


Loops in Python allow us to execute a group of statements several
times. Lets take an example to understand why loops are used in
python.
Flow Control
 What is for loop and while loop?
 Loop control statements
Conditional Iterative Transfer
Statements Statements Statements

1. for
1. if 1. Break
2. while
2. If-else 2. Continue
3. If-elif-else 3. pass
4. Nested if else

Conditional Statements in Python

Conditional statements in Python support the usual logical conditions


from mathematics.
For example:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to : a >= b
These statements can be used in several ways, most commonly
in if statement.

Government Polytechnic, Pune 11


Dr. S. P. Narote

Conditional Statements in Python


 Conditional Statements performs different computations or actions depending
on conditions.
 In python, the following are conditional statements
o if
o if –else
o if – elif –else
If statement:
 The if statement is used to test a specific condition. If the condition is true, a block
of code (if-block) will be executed.
Syntax:
if condition:
statement1
statement2

If Statement : Python

Selection statement causes program control to be


transferred to a specific condition based on that
condition is true or false
if else statement
An if statement is written using the ‘if’ keyword,
The syntax is the keyword ‘if’ followed with the
condition.
Selection

Government Polytechnic, Pune 12


Dr. S. P. Narote

If Statement : Python

Python if Statement Syntax if test expression:


statement(s)

 The program evaluates the test expression and will execute


statement(s) only if the test expression is True.
 If the test expression is False, the statement(s) is not executed.
 In Python, the body of the if statement is indicated by the
indentation. The body starts with an indentation and the first
unindented line marks the end.
 Python interprets non-zero values as True. None and 0 are
interpreted as False.

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.

Government Polytechnic, Pune 13


Dr. S. P. Narote

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

Government Polytechnic, Pune 14


Dr. S. P. Narote

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")

Government Polytechnic, Pune 15


Dr. S. P. Narote

If else

# If else
x,y =2,8
if(x < y):
b = "x is less than y"
print(b)

• Define two variables x, y = 2, 8


• if Statement in Python checks for condition x<y which is True in this
case
• The variable b is set to “x is less than y.”
• Print(b) will output the value of variable b which is “x is less than y”

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 Statement in Python checks for condition x<y which is True in this


case
• The variable b is set to “x is less than y.”
• Error

Government Polytechnic, Pune 16


Dr. S. P. Narote

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

Government Polytechnic, Pune 17


Dr. S. P. Narote

If else and elseif

# If else and elseif (elif)


x,y =9,9

if(x < y):


b = "x is less than y“
elif (x == y):
b= "x is same as y"
else:
b= "x is greater than y"
print(b)

Conditional Statements in Python


Program to find maximum number from given three numbers using if –elif-else

a=int(input("Enter a value : "))


b=int(input("Enter b value : ")) Output:
c=int(input("Enter c value : ")) Enter a value: 20
Enter b value: 35
if (a>b) and (a>c):
Enter c value: 10
print("Maximum value is :",a)
Maximum value is: 35
elif (b>a) and (b>c):
print("Maximum value is :",b)
else:
print("Maximum value is :",c)

Government Polytechnic, Pune 18


Dr. S. P. Narote

Loop Statements in Python


 Sometimes we may need to alter the flow of the program. If the execution of a
specific code may need to be repeated several numbers of times then we can go for
loop statements.
 In python, the following are loop statements
o while loop
o for loop
while loop:
 With the while loop we can execute a set of statements as long as a condition is
true. The while loop is mostly used in the case where the number of iterations is
not known in advance.
Syntax:
while expression:
Statement(s)

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 itarator_variable in sequence_name:


Statements
...
Statements

Government Polytechnic, Pune 19


Dr. S. P. Narote

For Loop
# Print numbers from 1 to 5
for i in range(5): Range Function
print(i) Body of the for loop

for i in range (5) range(5)= start =0, stop=5, step=1

Start Ist iteration i0 0

Start IInd iteration i1 1


Start 3rd iteration i2 2 Output
Start 4th iteration i3 3
Start 5thiteration i4 4

For loop
# Print numbers
numbers= [1,2, 3, 4,5]
for number in numbers
print(i)
Output
1
2
3 Output
4
5

Government Polytechnic, Pune 20


Dr. S. P. Narote

For Loops

• The execution starts and checks if the


condition is True or False.
• A condition could be any logic that we want
to test in our program.
• If its true it will execute the body of the loop
and if its false, It will exit the loop.

states = [“maharashtra", “goa", “gujrat"] maharashtra


for x in states: goa
print(x) gujrat

Syntax of for loop


for value in sequence:
Syntax of the Python for loop {loop body}
• First word of the statement starts with the keyword “for” which signifies the
beginning of the for loop.
• The iterator variable which iterates over the sequence and can be used
within the loop to perform various functions
• “in” keyword in Python which tells the iterator variable to loop for elements
within the sequence
• Finally, we the sequence variable which can either be a list, a tuple, or any
other kind of iterator.
• The statements part of the loop is where you can play around with the
iterator variable and perform various function

Government Polytechnic, Pune 21


Dr. S. P. Narote

Print individual letters of a string using the for loop

word="anaconda"
for letter in word:
print (letter)

Output
a
n
a
c
o
n
d
a

Using the for loop to iterate over a Python list or tuple


words= ["Apple", "Banana", "Car", "Dolphin" ]
for word in words:
print (word)

Output

Apple
Banana
Car
Dolphin

Government Polytechnic, Pune 22


Dr. S. P. Narote

Looping over the elements of a tuple here


nums = (1, 2, 3, 4)
sum_nums = 0
for num in nums:
sum_nums = sum_nums + num
print(f'Sum of numbers is {sum_nums}’)

Output
Sum of numbers is 10

Nesting Python for loops


words= ["Apple", "Banana" ]
for word in words:
#This loop is fetching word from the list
print ("The following lines will print each letters of "+word)
for letter in word:
#This loop is fetching letter for the word
print (letter)
print("") #This print is used to print a blank line
Output

Government Polytechnic, Pune 23


Dr. S. P. Narote

for loop and range() function

 range (a)
range(a,b)
range(a,b,c)

range(a) : Generates a sequence of numbers from 0 to a, excluding a, incrementing by 1.


for <variable> in range(<number>):
>>> for a in range(3):
print(a)

0
1
2

for loop and range() function


range(a,b): Generates a sequence of numbers from a to b
excluding b, incrementing by 1

for <variable> in range(“start_number”, “end_number”):

>>> for a in range(2,6):


print(a)

2
3
4
5

Government Polytechnic, Pune 24


Dr. S. P. Narote

for loop and range() function


range(a,b,c): Generates a sequence of numbers from a to b
excluding b, incrementing by c

for <variable> in range(“start_number”, “end_number”,”increment”):

>>> for a in range(2,19,5):


print(a)

2
7
12
17

Python for loop with range() function


# Output
for x in range(3):
# Printing: 0
print("Printing:", x)
# Printing: 1
# Printing: 2

for n in range(1, 10, 3):


print("Printing with step:", n)

# Output
Printing with step: 1
Printing with step: 4
Printing with step: 7

Government Polytechnic, Pune 25


Dr. S. P. Narote

Using else with for loop

 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

Python Break statement


 The break is a keyword in python which is used to bring the program control out of the
loop.
 The break statement breaks the loops one by one, i.e., in the case of nested loops, it
breaks the inner loop first and then proceeds to outer loops.
 The break is commonly used in the cases where we need to break the loop for a given
condition.
 The break statement terminates the loop containing it.
 Control of the program flows to the statement immediately after the body of the loop.
 If the break statement is inside a nested loop (loop inside another loop),
the break statement will terminate the innermost loop.

Syntax of break
 break

Government Polytechnic, Pune 26


Dr. S. P. Narote

Break statement with for loop


Flowchart Working of break statement

Python Break statement

# Use of break statement inside the loop


for val in "string":
if val == "i":
break
print(val)

print("The end")

s
t
r
The end

Government Polytechnic, Pune 27


Dr. S. P. Narote

Python Continue Statement


Flowchart Working of continue statement

Python Continue Statement


# Program to show the use of continue statement inside loops

for val in "string":


if val == "i":
continue
print(val)

print("The end")

s
t
r
n
g
The end

Government Polytechnic, Pune 28


Dr. S. P. Narote

Iteration or Looping

 Python provides two types of loops


1. While loop
2. For loop

Python supports standard comparison operations


a == b True if a and b are equal.
a != b True if a and b are not equal.
a>b True if a is greater than b.
a >= b True if a is equal or greater than b.
a<b True if a is less than b.
a <= b True if a is equal or less than b.

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

Government Polytechnic, Pune 29


Dr. S. P. Narote

Working of While loop


# While loop syntax
while (condition):
statement

• First, the expression is evaluated. If it returns true, control is passed to the


indented statement(s) inside the while loop.
• All the statements that are indented to the right below the while loop for
the body of the while loop and are executed.
• Once the statements are executed, control is again passed to the
expression, and the expression is evaluated again. If it returns true, the
body is executed again. This repeats until the expression returns false.
• Once the while loop break, control passed to the next unindented line of
the while loop

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.

Government Polytechnic, Pune 30


Dr. S. P. Narote

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")

• The objective is to print the “Hello GPP ” string 5 times.


• We took a variable count and initialized it to 0
• The expression ‘count < 5’ is evaluated, and since 0 < 5, control goes inside the while loop
• The ‘print’ statement and count = count + 1 statement, which is uniformly indented from the
body of the while loop. They are both executed.
• The string is printed to output once, and the count value gets incremented by 1.
• Now, control goes back to the expression ‘count < 5’. And since 1 < 5, control again goes inside
the while loop.
• This process is repeated till the count value is incremented to 5, and the print statement has
been executed a total of 5 times.
• Now, since the condition 5 < 5 returns false, the loop breaks, the body of the while loop is not
executed, and the control jumps to the next statement after the while statement.

While loop with else


# While loop syntax
while (condition):
statement
else :
statement

• 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.

Government Polytechnic, Pune 31


Dr. S. P. Narote

# Python program to illustrate


# while loop Example Output
Hello GPP
count = 0 Hello GPP
# define while loop Hello GPP
while (count < 5): Hello GPP
count = count + 1 Hello GPP
print("Hello GPP") String is printed 5 times
else :
print (“String is printed 5 times”)
• The objective is to print the “Hello GPP ” string 5 times.
• We took a variable count and initialized it to 0
• The expression ‘count < 5’ is evaluated, and since 0 < 5, control goes inside the while loop
• The ‘print’ statement and count = count + 1 statement, which is uniformly indented from the body of the
while loop. They are both executed.
• The string is printed to output once, and the count value gets incremented by 1.
• Now, control goes back to the expression ‘count < 5’. And since 1 < 5, control again goes inside the while loop.
• This process is repeated till the count value is incremented to 5, and the print statement has been executed a
total of 5 times.
• Now, since the condition 5 < 5 returns false, the loop breaks, the body of the while loop is not executed, and
the control jumps to the next statement after the while statement.
• Now, the body of else statements gets executed, and the print statement is executed.
• Then, the flow of control goes to the next statement after the while-else statement.

While with else Loop


Using else with while loop
 Python enables us to use the while loop with the else block also. The else block is
executed when the condition given in the while statement becomes false.

Example: Output:
i=1; 1
while i<=3: 2
print(i); 3
i=i+1; while loop terminated
else:
print("while loop termina
ted")

Government Polytechnic, Pune 32


Dr. S. P. Narote

Python break and continue Statements


Python provides two keywords that terminate a loop iteration
prematurely:
break : break statement immediately terminates a loop entirely.
Program execution proceeds to the first statement following the loop
body.
continue : continue statement immediately terminates the current loop
iteration. Execution jumps to the top of the loop, and the controlling
expression is re-evaluated to determine whether the loop will execute
again or terminate.

Difference between break and continue


Flow chart for Break statement Flow chart for Continue statement

Enter loop Enter loop

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

Government Polytechnic, Pune 33


Dr. S. P. Narote

Python Continue Statement for while & for loop


Flow chart for Continue statement
Working of continue statement
Enter loop

False
Expression
of loop

True

Yes
Continue

No
Exit loop
Remaining part
of loop

Python program to illustrate use of continue


# Python program to illustrate 4
# continue Output 3
n=5 1
while n > 0: 0
n -= 1 Loop ended
if n == 2:
continue
print(n)
print('Loop ended.’)

Here when n is 2, the continue statement causes termination of that iteration.


Thus, 2 isn’t printed. Execution returns to the top of the loop, the condition is re-
evaluated, and it is still true. The loop resumes, terminating when n becomes 0,
as previously.

Government Polytechnic, Pune 34


Dr. S. P. Narote

Python program to illustrate use of continue


# Python program to illustrate Output
# continue The num has value: 1
num = 0 The num has value: 2
for i in range(10): The num has value: 3
num += 1 The num has value: 4
if num == 8: The num has value: 5
break The num has value: 6
print("The num has value:", num) The num has value: 7
print("Out of loop") Out of loop

Here when n is 8, the continue statement causes termination of that iteration.


Thus, 2 isn’t printed. Execution returns to the top of the loop, the condition is re-
evaluated, and it is still true. The loop resumes, terminating when n becomes 0, as
previously.

Break statement for & while loop


Flow chart for Break statement
Working of break statement
Enter loop

False
Expression
of loop

True

Yes
Break

No
Exit loop
Remaining part
of loop

Government Polytechnic, Pune 35


Dr. S. P. Narote

Break

n=5 4
while n > 0: 3
n -= 1 Loop ended
if n == 2:
break
print(n)
print('Loop ended')

When n becomes 2, the break statement is executed. The loop is


terminated completely, and program execution jumps to
the print() statement on line 7.

Difference : Break & Continue

Parameter Break Continue


Allows you to exit from an overall loop construct Yes No

Can be used by switch statement Yes No

The control exits immediately from a loop


Yes No
construct

Causes a loop to termination Yes No

Can be used with “label” Yes No

Syntax break continue

Government Polytechnic, Pune 36


Dr. S. P. Narote

Key Takeaways

• While loop is indefinite iteration


• While loop in python runs until the "while" condition is satisfied.
• While loop repeats code while the expression is True
• While loop exits the loop if the expression is False
• The break and continue statements change the loop behavior
• The "while true" loop in python runs without any conditions until the break
statement executes inside the loop.
• To run a statement if a python while loop fails, the programmer can
implement a python "while" with else loop.
• Python does not support the "do while" loop. Although we can implement
this loop using other loops easily.

For vs While Loop in Python


Basis of Comparison For Loop While Loop
for object in sequence: while condition:
Declaration
<indentation>body <indentation>body

Initialization, condition checking, and iteration Only initialization and condition


Format
statements are written at the top checking is written at the top

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.

Government Polytechnic, Pune 37


Dr. S. P. Narote

Example: For loop to generate 2D array


Write a Python program to generate a m (row) and n (column) two-dimensional
array. The element value in the i-th row and j-th column of the array should be i*j

Array : irow = 0,1.., m-1 jcol = 0,1, n-1

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

Government Polytechnic, Pune 38

You might also like