You are on page 1of 20

Python

Loops and Iteration


n=5 Repeated Steps
No Yes Program:
n>0? Output:

print n n=5 5
while n > 0 : 4
print n 3
n = n -1
n=n–1 2
print 'Blastoff!' 1
print n Blastoff!
print 'Blastoff' 0
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
An Infinite Loop
No Yes
n>0?

print 'Lather' n=5


while n > 0 :
print 'Rinse' print 'Lather'
print 'Rinse'
print 'Dry off!'

print 'Dry off!'

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

while True: > hello there


line = raw_input('> ') hello there
if line == 'done' : > finished
break finished
print line > done
print 'Done!' Done!
while True: No Yes
True ?
line = raw_input('> ')
if line == 'done' :
....
break
print line
print 'Done!' break

...

print 'Done'
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
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"


A Simple Definite Loop
for i in [5, 4, 3, 2, 1] : 5
print i 4
print 'Blastoff!' 3
2
1
Blastoff!
A Simple Definite Loop
friends = ['Joseph', 'Glenn', 'Sally'] Happy New Year: Joseph
for friend in friends : Happy New Year: Glenn
print 'Happy New Year: ', friend Happy New Year: Sally
print 'Done!' Done!
The range() function (revisited)
x = range(5)
• range() is a built-in function print x
that allows you to create a [0, 1, 2, 3, 4]
sequence of numbers in a
range x = range(3, 7)
print x
• Very useful in “for” loops
[3, 4, 5, 6]
which are discussed later in
the Iteration chapter
x = range(10, 1, -2)
• Takes as an input 1, 2, or 3 print x
[10, 8, 6, 4, 2]
arguments. See examples.
A Simple Definite Loop iterating
over a range 7
6
for i in range(7, 0, -1) : 5
print i 4
print 'Blastoff!' 3
2
1
Blastoff!
Looping through a Set
Before
9
print 'Before' 41
for thing in [9, 41, 12, 3, 74, 15] : 12
print thing 3
74
print 'After' 15
After
Counting in a Loop
Before 0
zork = 0
19
print 'Before', zork
2 41
for thing in [9, 41, 12, 3, 74, 15] :
3 12
zork = zork + 1
43
print zork, thing
5 74
print 'After', zork
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.
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

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.
Finding the Average in a Loop
count = 0
Before 0 0
sum = 0
199
print 'Before', count, sum
2 50 41
for value in [9, 41, 12, 3, 74, 15] :
3 62 12
count = count + 1
4 65 3
sum = sum + value
5 139 74
print count, sum, value
6 154 15
print 'After', count, sum, sum / count
After 6 154 25

An average just combines the counting and sum patterns


and divides when the loop is done.
Filtering in a Loop

print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
if value > 20: Before
print 'Large number',value Large number 41
print 'After' Large number 74
After

We use an if statement in the loop to catch / filter the values


we are looking for.
Control flow tools
for letter in "aeiou":
print "vowel: ", letter
for i in [1,2,3]:
print i
for i in range(0,3):
print i
The for loop has the following general form.
for var in sequence:
statements

vowel: a
vowel: e
vowel: i
vowel: o
If a sequence contains an expression list, it is evaluated vowel: u
first. Then, the first item in the sequence is assigned to 1
the iterating variable var. Next, the statements are 2
executed. Each item in the sequence is assigned to var, 3
0
and the statements are executed until the entire 1
sequence is exhausted. 2

For loops may be nested with other control flow tools such
as while loops and if statements.
Example

write a program that reads in the grades


of 50 students in a course (out of 100
points each ) and then count the number
of A students ( grade > 85 ) and the
number of B students (grade > 75 ).
Count-Controlled Loop Example

Use a while loop to read the


100 blood pressures and find
their total
Example

Write a program to display all the numbers

divisible by 5 in the range 0 to 5000.

19
Example

Assume you put 1000 pounds in a projects that returns a profit of


about 5% per year. How long will it take for your money to
double ?

Assume you put 5000 pounds in a projects that returns a profit of


about 10% per year. How much money will you have in 5 years ?

You might also like