Programming‎ > ‎Python‎ > ‎

05-Iteration

Loops and Iteration

An Infinite Loop

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

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

Breaking Out of the 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:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'

Continue

The continue statement ends the current iteration and jumps to
the top of the loop and starts the next iteration

while True:
line = raw_input('> ')
if line == '#' :
continue
if line == 'done' :
break
print line
print '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
• 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”

for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'

The "is" and is not " Operator

• Python has an is operator that can be used in logical expressions
• Implies “is the same as”
• Similar to, but stronger than ==
• is not also is a logical operator

smallest = None
print 'Before'
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
smallest = value
elif value < smallest :
smallest = value
print smallest, value
print 'After', smallest