Week 05 Looping Statements (for Loop, While Loop and Nested Loop) - Subash
Week 05 Looping Statements (for Loop, While Loop and Nested Loop) - Subash
Python Programming
finding sum, finding max, average etc.
• Apply nested loops
• Use the keywords break and continue
2
01/17/2025
Contents & Structure
Iterative (loops) structures in python
Python Programming
Nested loops
Infinite loops
3 ‹#›
01/17/2025
Control Structure - Repetition
yes Loop
Condition
Statement(s)
no
Python Programming
4
01/17/2025
Repetition: Computer View
Continuing a process as long as a certain condition
has been met. How old are you?
Python Programming
21! Minus 21!
6 ‹#›
Repetition Structure in Python
01/17/2025
Used when
you know
how many
FOR
times to
repeat / do
something
Used when
you do not
know how
Python Programming
WHILE
many
times to
repeat.
8 ‹#›
How To Determine If Loops Can Be
01/17/2025
Applied
Python Programming
9 ‹#›
How To Determine If Loops Can Be
01/17/2025
Applied
• Something needs to occur multiple
times (generally it will repeat itself as
long as some condition has been met). Flowchart
N
Play again?
Y
Run game again
Python Programming
END GAME
Pseudo code
While the player wants to play
Run the game again
10 ‹#›
Pre-Test Loops In Python
01/17/2025
1. While
2. For
Characteristics:
1. The stopping condition is checked before the body executes.
2. These types of loops execute zero or more times.
Python Programming
15
slide 15
‹#›
01/17/2025
Post-Loops In Python
• Note:this type of looping construct has not been implemented with
this language (Python).
• But many other languages do implement post test loops.
Characteristics:
The stopping condition is checked after the body executes.
These types of loops execute one or more times.
Python Programming
16 ‹#›
01/17/2025
While Loop in Python
• While loops are called "indefinite loops" because
they keep going until a logical condition becomes
false.
• This
type of loop can be used if it’s not known in
advance how many times that the loop will repeat.
Python Programming
• Themost powerful type of loop, any other type of
loop can be simulated with a while loop.
17
01/17/2025
Syntax (while loop) condition = True
while(condition):
while(condition): print(“Hello”)
statement 1
statement 2 condition = True
.
. False
Python Programming
condition
?
.
True
Display Hello
18
01/17/2025
Countdown Loop – Example
i = 10
while (i >= 1):
print("i =", i)
i = i – 1 #Sentinel Data
print("Done!")
Python Programming
20 ‹#›
01/17/2025
Creating a for Loop
• To create a for loop, you start with
for,
followed by a variable for each element,
followed by in,
followed by the sequence you want to loop through,
followed by a :, and
finally, the loop body.
Python Programming
Syntax:
total = 0
for i in range (1, 4, 1):
total = total + i
print("i=", i, "\t total=", total)
print("Done!")
Python Programming
3) Execute body
25 ‹#›
01/17/2025
For loop in Python
Example – 1:
Output
for i in range(0,5,1):
???
print(i)
Example – 2:
Python Programming
for i in Output
range(1,10,2): ???
print(i)
26
01/17/2025
Counting Down With A For Loop
Output
i = 0 ???
total = 0
for i in range (10, 0, -1):
print(f"{i}")
print("Done!")
Python Programming
28 ‹#›
Loop Increments Need Not Be
01/17/2025
Limited To One
• While: while_increment5.py
i = 0
while (i <= 100):
print("i =", i)
i = i + 5
print("Done!")
• For: for_increment5.py
for i in range (0, 105, 5):
Python Programming
print("i =", i)
print("Done!")
38 ‹#›
01/17/2025
Sentinel Loops
A sentinel loop continues to process data until
reaching a special value that signals the end.
Python Programming
The sentinel must be distinguishable from the data
since it is not processed as part of the data.
3939 ‹#›
01/17/2025
Sentinel Loops – Example
Which data is the Sentinel
total = 0 for given loop?
num = 0
while(num >= 0):
num = input ("Enter a non-negative integer:")
num = int(num) If value of n is negative, then
if (num >= 0): loop will break.
Python Programming
total = total + num
print("Sum total of the series:", total)
40 ‹#›
Using else Statement with While
01/17/2025
Loop
Python supports to have an else statement associated
with a loop statement.
Syntax:
Python Programming
while expr:
statement(s)
else:
additional_statement(s)
42 ‹#›
Using else Statement with While
01/17/2025
Loop - Example
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
Python Programming
print(count, " is not less than 5")
43 ‹#›
01/17/2025
Nested Loops
Python Programming
number of numbers on a line in the file (separated
by commas), rather than one per line.
45 ‹#›
01/17/2025
Nested Loops
• One loop executes inside of another loop(s).
• Example structure:
Outer loop (runs n times)
Inner loop (runs m times)
Body of inner loop (runs n x m times)
Python Programming
j = 1
while (j <= 3):
print("i = ", i, " j = ", j)
j = j + 1
i = i + 1
print("Done!")
46 ‹#›
What is the use of break and
01/17/2025
continue in Python?
break and continue statements can alter the flow of a normal loop
Loops iterate over a block of code until test expression is false, but
sometimes we wish to terminate the current iteration or even the whole
loop without checking test expression
Python Programming
break and continue statements are used in these cases
47 ‹#›
01/17/2025
Python 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
Python Programming
Syntax of break statement
break
48 ‹#›
Flowchart of break
‹#›
print(val)
break
print(val)
print("The end")
Python Programming
50
01/17/2025
Continue Statement
Is used to skip the rest of the code
inside a loop for the current iteration
only
Python Programming
Syntax of continue Statement
continue
51 ‹#›
Flowchart of continue
Python Programming
53 ‹#›
01/17/2025
pass statement
pass is a null statement
Python Programming
Syntax of pass
pass
56 ‹#›
01/17/2025
pass - Example
strings = {'p', 'a', 's', 's'}
pass
Python Programming
57 ‹#›
01/17/2025
Infinite Loop
Python Programming
• Occurs when programmer forgets to include stopping code in the loop
58 ‹#›
01/17/2025
Infinite Loops
• Infinite loops never end (the stopping condition is never met).
• They can be caused by logical errors:
The loop control is never updated (Example 1 – below).
The updating of the loop control never brings it closer to the stopping condition (Example 2
– next slide).
• Example 1: infinite1.py
i = 1
while (i <= 10):
print("i = ", i)
Python Programming
i = i + 1
59 ‹#›
01/17/2025
Infinite Loops
• Example 2: infinite2.py
i = 10
print("i = ", i)
i = i + 1
print("Done!")
Python Programming
60 ‹#›
Exercises:
01/17/2025
in a Loop
sum = 0.0
count = 0
x = eval(input("Enter a number (negative to quit) >> "))
while x >= 0:
sum = sum + x
count = count + 1
x = eval(input("Enter a number (negative to quit) >> "))
Python Programming
print("\nThe average of the numbers is", sum / count)
An average just combines the counting and sum patterns and divides when
the loop is done.
62
01/17/2025
More Example – Filter a list
numbers = [4, 23, 32, 12, 88]
for value in numbers:
if value >= 20:
print('Large number', value)
print('Done’)
Python Programming
Use an if statement in the loop to catch / filter the values we are looking
for.
63
Recap: What Looping Constructs Are
01/17/2025
Available In Python/When To Use Them
Construct When To Use
Pre-test loops You want the stopping condition to be checked before the loop body is executed
(typically used when you want a loop to execute zero or more times).
While The most powerful looping construct: you can write a ‘while’ loop to mimic the
behavior of any other type of loop. In general, it should be used when you want a
pre-test loop which can be used for most any arbitrary stopping condition e.g.,
execute the loop as long as the user doesn’t enter a negative number.
Post-test: None in Python You want to execute the body of the loop before checking the stopping condition
Python Programming
(typically used to ensure that the body of the loop will execute at least once). The
logic can be simulated with a while loop.
64
slide 64
‹#›
01/17/2025
Summary / Recap of Main Points
• Iterative (loops) structures in python
• While loop as Condition-Controlled Loop and sentinel controlled
• For loop as Count-Controlled and enhanced loop
• Break and continue
• Nested loops
• Infinite loops
Python Programming
65
END
Python Programming
Python Programming 01/17/2025
01/17/2025
66
66