Loop and Iterations
Loop and Iterations
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 '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
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
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
19
Example