Loops and Iteration
Sectio 8&9
Prepared by :Abdullah Emam
Compound statements
Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way.
The if, while and for statements implement traditional control flow constructs.
The if statement is used for conditional execution:
The while statement is used for repeated execution as long as an expression is true:
The for statement is used to iterate over the elements of a sequence (such as a
string, tuple or list) or other iterable object:
By: Abdullah Emam
n=5 Repeated Steps
Output:
No Yes Program:
n>0? 5
n = 5 4
print(n) while n > 0 :
3
print(n)
n = n – 1 2
n = n -1 print('Blastoff!') 1
print(n) Blastoff!
0
Loops (repeated steps) have iteration variables that
print('Blastoff') change each time through a loop. Often these iteration
variables go through a sequence of numbers.
By: Abdullah Emam
n=5 An Infinite Loop
No Yes
n>0?
n = 5
while n > 0 :
print('Lather') print('Lather')
print('Rinse')
print('Rinse') print('Dry off!')
print('Dry off!') What is wrong with this loop?
By: Abdullah Emam
n=0 Another Loop
No Yes
n>0?
n = 0
while n > 0 :
print('Lather') print('Lather')
print('Rinse')
print('Rinse') print('Dry off!')
print('Dry off!') What is this loop doing?
By: Abdullah Emam
Single statement while block
By: Abdullah Emam
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
By: Abdullah Emam
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
By: Abdullah Emam
No Yes
while True: True ?
line = input('> ')
if line == 'done' :
....
break
print(line)
print('Done!')
break
...
print('Done')
By: Abdullah Emam
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
By: Abdullah Emam
Finishing an Iteration with
continue
The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = input('> ')
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done!
By: Abdullah Emam
No
True ? Yes
while True:
line = raw_input('> ') ....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print(line)
...
print('Done!')
print('Done')
By: Abdullah Emam
Indefinite Loops
• While loops are called “indefinite loops” because they keep
going until a logical condition becomes False
• The loops we have seen so far are pretty easy to examine to see
if they will terminate or if they will be “infinite loops”
• Sometimes it is a little harder to be sure if a loop will terminate
By: Abdullah Emam
Definite Loops
Iterating over a set of items…
Definite Loops
• Quite often we have a list of items of the lines in a file -
effectively a finite set of things
• We can write a loop to run the loop once for each of the items in
a set using the Python for construct
• These loops are called “definite loops” because they execute an
exact number of times
• We say that “definite loops iterate through the members of a set”
By: Abdullah Emam
A Simple Definite Loop
5
for i in [5, 4, 3, 2, 1] :
print(i)
4
print('Blastoff!') 3
2
1
Blastoff!
By: Abdullah Emam
A Definite Loop with Strings
Happy New Year: Joseph
friends = ['Joseph', 'Glenn', 'Sally'] Happy New Year: Glenn
for friend in friends : Happy New Year: Sally
print('Happy New Year:', friend)
print('Done!')
Done!
By: Abdullah Emam
A Simple Definite Loop
Yes No
Done? Move i ahead 5
for i in [5, 4, 3, 2, 1] : 4
print(i) 3
print(i) print('Blastoff!')
2
1
Blastoff!
Definite loops (for loops) have explicit iteration variables
print('Blast off!') that change each time through a loop. These iteration
variables move through the sequence or set.
By: Abdullah Emam
Looking at in...
• The iteration variable
“iterates” through the Five-element
sequence (ordered set) sequence
Iteration variable
• The block (body) of code is
executed once for each for i in [5, 4, 3, 2, 1] :
value in the sequence print(i)
• The iteration variable moves
through all of the values in
the sequence
By: Abdullah Emam
No • The iteration variable “iterates”
Yes
Done? Move i ahead through the sequence (ordered
set)
print(i)
• The block (body) of code is
executed once for each value in
the sequence
• The iteration variable moves
through all of the values in the
for i in [5, 4, 3, 2, 1] :
print(i)
sequence
By: Abdullah Emam
i=5
No print(i)
Yes
Done? Move i ahead i=4
print(i)
print(i)
i=3
print(i)
i=2
for i in [5, 4, 3, 2, 1] : print(i)
print(i)
i=1
print(i)
By: Abdullah Emam
Loop Idioms:
What We Do in Loops
Note: Even though these examples are simple,
the patterns apply to all kinds of loops
By: Abdullah Emam
Making “smart” loops
Set some variables to
initial values
for thing in data:
The trick is “knowing” something
Look for something or
about the whole loop when you
do something to each
are stuck writing code that only
entry separately,
sees one entry at a time updating a variable
Look at the variables
By: Abdullah Emam
Looping Through a Set
$ python [Link]
print('Before')
Before
for thing in [9, 41, 12, 3, 74, 15] : 9
print(thing) 41
print('After')
12
3
74
15
After
By: Abdullah Emam
What is the Largest Number?
By: Abdullah Emam
What is the Largest Number?
By: Abdullah Emam
What is the Largest Number?
41
By: Abdullah Emam
What is the Largest Number?
12
By: Abdullah Emam
What is the Largest Number?
By: Abdullah Emam
What is the Largest Number?
74
By: Abdullah Emam
What is the Largest Number?
15
By: Abdullah Emam
What is the Largest Number?
By: Abdullah Emam
What is the Largest Number?
3 41 12 9 74 15
By: Abdullah Emam
What is the Largest Number?
largest_so_far -1
By: Abdullah Emam
What is the Largest Number?
largest_so_far 3
By: Abdullah Emam
What is the Largest Number?
41
largest_so_far 41
By: Abdullah Emam
What is the Largest Number?
12
largest_so_far 41
By: Abdullah Emam
What is the Largest Number?
largest_so_far 41
By: Abdullah Emam
What is the Largest Number?
74
largest_so_far 74
By: Abdullah Emam
What is the Largest Number?
15
74
By: Abdullah Emam
What is the Largest Number?
3 41 12 9 74 15
74
By: Abdullah Emam
Finding the Largest Value
$ python [Link]
largest_so_far = -1
Before -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : 9 9
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
We make a variable that contains the largest value we have seen so far. If the current
number we are looking at is larger, it is the new largest value we have seen so far.
By: Abdullah Emam
More Loop Patterns…
By: Abdullah Emam
Counting in a Loop
$ python [Link]
zork = 0 Before 0
print('Before', zork) 19
for thing in [9, 41, 12, 3, 74, 15] :
2 41
zork = zork + 1
print(zork, thing) 3 12
print('After', zork) 43
5 74
6 15
After 6
To count how many times we execute a loop, we introduce a counter variable
that starts at 0 and we add one to it each time through the loop.
By: Abdullah Emam
Summing in a Loop
$ python [Link]
zork = 0 Before 0
print('Before', zork) 99
for thing in [9, 41, 12, 3, 74, 15] :
50 41
zork = zork + thing
print(zork, thing) 62 12
print('After', zork) 65 3
139 74
154 15
After 154
To add up a value we encounter in a loop, we introduce a sum variable that
starts at 0 and we add the value to the sum each time through the loop.
By: Abdullah Emam
Finding the Average in a Loop
$ python [Link]
count = 0 Before 0 0
sum = 0
199
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15] : 2 50 41
count = count + 1 3 62 12
sum = sum + value 4 65 3
print(count, sum, value) 5 139 74
print('After', count, sum, sum / count) 6 154 15
After 6 154 25.666
An average just combines the counting and sum patterns and
divides when the loop is done.
By: Abdullah Emam
Filtering in a Loop
print('Before') $ python [Link]
for value in [9, 41, 12, 3, 74, 15] : Before
if value > 20: Large number 41
print('Large number',value)
print('After')
Large number 74
After
We use an if statement in the loop to catch / filter the
values we are looking for.
By: Abdullah Emam
Search Using a Boolean Variable
$ python [Link]
found = False
Before False
print('Before', found) False 9
for value in [9, 41, 12, 3, 74, 15] : False 41
if value == 3 : False 12
found = True True 3
print(found, value) True 74
print('After', found)
True 15
After True
If we just want to search and know if a value was found, we use a variable that
starts at False and is set to True as soon as we find what we are looking for.
By: Abdullah Emam
How to Find the Smallest Value
$ python [Link]
largest_so_far = -1
Before -1
print('Before', largest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : 9 9
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
How would we change this to make it find the smallest value in the list?
By: Abdullah Emam
Finding the Smallest Value
smallest_so_far = -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far, the_num)
print('After', smallest_so_far)
We switched the variable name to smallest_so_far and switched the > to <
By: Abdullah Emam
Finding the Smallest Value
$ python [Link]
smallest_so_far = -1
Before -1
print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : -1 9
if the_num < smallest_so_far : -1 41
smallest_so_far = the_num -1 12
print(smallest_so_far, the_num) -1 3
-1 74
print('After', smallest_so_far) -1 15
After -1
We switched the variable name to smallest_so_far and switched the > to <
By: Abdullah Emam
Finding the Smallest Value
smallest = None $ python [Link]
print('Before') Before
for value in [9, 41, 12, 3, 74, 15] : 99
if smallest is None :
9 41
smallest = value
elif value < smallest : 9 12
smallest = value 33
print(smallest, value) 3 74
print('After', smallest) 3 15
After 3
We still have a variable that is the smallest so far. The first time through the loop
smallest is None, so we take the first value to be the smallest.
By: Abdullah Emam
The is and is not Operators
• Python has an is operator
smallest = None that can be used in logical
print('Before') expressions
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
smallest = value
• Implies “is the same as”
elif value < smallest :
smallest = value • Similar to, but stronger than
print(smallest, value) ==
print('After', smallest)
• is not also is a logical
operator
By: Abdullah Emam
Glossary
accumulator
A variable used in a loop to add up or accumulate a result.
counter
A variable used in a loop to count the number of times something happened. We initialize a counter to
zero and then increment the counter each time we want to “count” something.
decrement
An update that decreases the value of a variable.
initialize
An assignment that gives an initial value to a variable that will be updated.
increment
An update that increases the value of a variable (often by one).
infinite loop
A loop in which the terminating condition is never satisfied or for which there is no terminating condition.
iteration
Repeated execution of a set of statements using either a function that calls itself or a loop.
By: Abdullah Emam
Summary
• While loops (indefinite) • For loops (definite)
• Infinite loops • Iteration variables
• Using break • Loop idioms
• Using continue • Largest or smallest
• None constants and variables
By: Abdullah Emam
Acknowledgements / Contributions