You are on page 1of 17

Iterations

Chapter 5
Loops
Loops (repeated steps) have iteration variables that change each
time through a loop. Often these iteration variables go through a
sequence of numbers.

n = 5
for x in range(5): while n > 0 :
print(x) print('Lather')

What is wrong with this loop?


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


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

• We say that “definite loops iterate through the members of a set”

• Definite loops (for loops) have explicit iteration variables that


move through the sequence or set.
A Simple Definite Loop
5
for i in [5, 4, 3, 2, 1] :
print(i)
4
print('Blastoff!') 3
2
1
Blastoff!
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!
Loop Idioms:
What We Do in Loops

Note: Even though these examples are simple,


the patterns apply to all kinds of loops
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


Finding the Largest Value
largest_so_far = -1 Before -1
print('Before', largest_so_far) 9 9
for elem in [9, 41, 12, 3, 74, 15] : 41 41
if elem > largest_so_far : 41 12
largest_so_far = elem
41 3
print(largest_so_far, elem)
74 74
print('After', largest_so_far) 74 15
After 74
Counting in a Loop
zork = 0
Before 0
print('Before', zork) 19
for thing in [9, 41, 12, 3, 74, 15] : 2 41
zork = zork + 1 3 12
print(zork, thing) 43
print('After', zork) 5 74
6 15
After 6
Summing in a Loop
zork = 0
Before 0
print('Before', zork) 99
for thing in [9, 41, 12, 3, 74, 15] : 50 41
zork = zork + thing 62 12
print(zork, thing) 65 3
print('After', zork) 139 74
154 15
After 154
Search Using a Boolean Variable
Before False
found = False False 9
print('Before', found) False 41
for value in [9, 41, 12, 3, 74, 15] :
False 12
if value == 3 :
found = True
True 3
print(found, value) True 74
print('After', found) True 15
After True
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
Summary
• While loops (indefinite) • For loops (definite)
• Infinite loops • Iteration variables
• Using break • Loop idioms
• Using continue • Largest or smallest
• None constants and variables
Exercise
• Write a program which repeatedly reads numbers until the user enters
“done”. Once “done” is entered, print out the total, count, and average of the
numbers. If the user enters anything other than a number, detect their
mistake using try and except and print an error message; then skip to the
next number.
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid input
Enter a number: 7
Enter a number: done
16 3 5.333333333333333

You might also like