Pythonlearn 05 Iterations
Pythonlearn 05 Iterations
1 2
print('Dry off!') What is wrong with this loop? print('Dry off!') What is this loop doing?
3 4
10/01/21
• It is like a loop test that can happen anywhere in the body of the • It is like a loop test that can happen anywhere in the body of the
loop loop
while True: > hello there while True: > hello there
line = input('> ') hello there line = input('> ') hello there
if line == 'done' : > finished if line == 'done' : > finished
break finished break finished
print(line) > done print(line) > done
print('Done!') Done! print('Done!')
Done!
5 6
while True:
No
True ?
Yes Finishing an Iteration with
line = input('> ')
if line == 'done' :
....
continue
break
The continue statement ends the current iteration and jumps to the
print(line)
print('Done!') top of the loop and starts the next iteration
break
while True:
> hello there
line = input('> ')
... if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
http://en.wikipedia.org/wiki/Transporter_(Star_Trek) print(line) > done
print('Done') print('Done!') Done!
7 8
10/01/21
9 10
Indefinite Loops
11 12
10/01/21
13 14
15 16
10/01/21
17 18
i=5
No print(i)
Yes
Done? Move i ahead i=4
Loop Idioms:
print(i)
print(i) What We Do in Loops
i=3
print(i)
i=2
Note: Even though these examples are simple,
print(i)
the patterns apply to all kinds of loops
for i in [5, 4, 3, 2, 1] :
print(i)
i=1
print(i)
19 20
10/01/21
21 22
23 24
10/01/21
41 12
25 26
9 74
27 28
10/01/21
15
29 30
3 41 12 9 74 15
largest_so_far -1
31 32
10/01/21
3 41
largest_so_far 3 largest_so_far 41
33 34
12 9
largest_so_far 41 largest_so_far 41
35 36
10/01/21
74 15
largest_so_far 74 74
37 38
39 40
10/01/21
Counting in a Loop
$ python countloop.py
zork = 0 Before 0
41 42
To add up a value we encounter in a loop, we introduce a sum variable that An average just combines the counting and sum patterns and
starts at 0 and we add the value to the sum each time through the loop. divides when the loop is done.
43 44
10/01/21
45 46
How would we change this to make it find the smallest value in the list? We switched the variable name to smallest_so_far and switched the > to <
47 48
10/01/21
We still have a variable that is the smallest so far. The first time through the loop
We switched the variable name to smallest_so_far and switched the > to <
smallest is None, so we take the first value to be the smallest.
49 50
51 52
10/01/21
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance ...
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.
53