Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

10/01/21

n=5 Repeated Steps


Output:
No Yes Program:
n>0? 5
Loops and Iteration print(n)
n = 5
while n > 0 :
print(n)
4
3
2
Chapter 5 n = n -1
n = n – 1
print('Blastoff!') 1
print(n) Blastoff!
0
Python for Everybody Loops (repeated steps) have iteration variables that
www.py4e.com print('Blastoff') change each time through a loop. Often these iteration
variables go through a sequence of numbers.

1 2

n=5 An Infinite Loop n=0 Another Loop


No Yes No Yes
n>0? n>0?
n = 5 n = 0
while n > 0 : while n > 0 :
print('Lather') print('Lather')
print('Lather') print('Lather')
print('Rinse') print('Rinse')
print('Rinse') print('Dry off!') print('Rinse') print('Dry off!')

print('Dry off!') What is wrong with this loop? print('Dry off!') What is this loop doing?

3 4
10/01/21

Breaking Out of a Loop Breaking Out of a Loop


• The break statement ends the current loop and jumps to the • The break statement ends the current loop and jumps to the
statement immediately following the loop statement immediately following the loop

• 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

Finishing an Iteration with No


continue True ? Yes
while True:
The continue statement ends the current iteration and jumps to the line = raw_input('> ') ....
top of the loop and starts the next iteration if line[0] == '#' :
continue
while True: if line == 'done' : continue
> hello there
line = input('> ') break
if line[0] == '#' : hello there
print(line)
continue > # don't print this ...
print('Done!')
if line == 'done' : > print this!
break print this!
print(line) > done
print('Done!') Done! print('Done')

9 10

Indefinite Loops

• While loops are called “indefinite loops” because they keep


going until a logical condition becomes False
Definite Loops
Iterating over a set of items…
• 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

11 12
10/01/21

Definite Loops A Simple Definite Loop


• Quite often we have a list of items of the lines in a file -
effectively a finite set of things 5
for i in [5, 4, 3, 2, 1] :
• We can write a loop to run the loop once for each of the items in print(i)
4
a set using the Python for construct print('Blastoff!') 3
2
• These loops are called “definite loops” because they execute an
exact number of times 1
Blastoff!
• We say that “definite loops iterate through the members of a set”

13 14

A Definite Loop with Strings A Simple Definite Loop


Yes No
Done? Move i ahead 5
Happy New Year: Joseph for i in [5, 4, 3, 2, 1] : 4
print(i) 3
friends = ['Joseph', 'Glenn', 'Sally'] Happy New Year: Glenn print(i) print('Blastoff!')
for friend in friends : 2
Happy New Year: Sally
print('Happy New Year:', friend) 1
print('Done!') Blastoff!
Done!
Definite loops (for loops) have explicit iteration variables
print('Blast off!') that change each time through a loop. These iteration
variables move through the sequence or set.

15 16
10/01/21

Looking at in... Yes


No • The iteration variable “iterates”
Done? Move i ahead through the sequence (ordered
• The iteration variable set)
“iterates” through the Five-element
print(i)
sequence (ordered set) sequence • The block (body) of code is
Iteration variable
executed once for each value in
• The block (body) of code is the sequence
executed once for each for i in [5, 4, 3, 2, 1] :
value in the sequence print(i) • The iteration variable moves
through all of the values in the
• The iteration variable moves for i in [5, 4, 3, 2, 1] :
sequence
through all of the values in print(i)
the sequence

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

Making “smart” loops Looping Through a Set


Set some variables to $ python basicloop.py
initial values Before
print('Before')
for thing in data: for thing in [9, 41, 12, 3, 74, 15] : 9
The trick is “knowing” something print(thing) 41
Look for something or print('After')
12
about the whole loop when you
do something to each
are stuck writing code that only 3
entry separately,
sees one entry at a time 74
updating a variable
15
After
Look at the variables

21 22

What is the Largest Number? What is the Largest Number?

23 24
10/01/21

What is the Largest Number? What is the Largest Number?

41 12

25 26

What is the Largest Number? What is the Largest Number?

9 74

27 28
10/01/21

What is the Largest Number? What is the Largest Number?

15

29 30

What is the Largest Number? What is the Largest Number?

3 41 12 9 74 15

largest_so_far -1

31 32
10/01/21

What is the Largest Number? What is the Largest Number?

3 41

largest_so_far 3 largest_so_far 41

33 34

What is the Largest Number? What is the Largest Number?

12 9

largest_so_far 41 largest_so_far 41

35 36
10/01/21

What is the Largest Number? What is the Largest Number?

74 15

largest_so_far 74 74

37 38

What is the Largest Number? Finding the Largest Value


$ python largest.py
largest_so_far = -1
Before -1
print('Before', largest_so_far)
9 9
3 41 12 9 74 15 for the_num in [9, 41, 12, 3, 74, 15] :
if the_num > largest_so_far : 41 41
largest_so_far = the_num 41 12
print(largest_so_far, the_num) 41 3
74 74
print('After', largest_so_far) 74 15
After 74
74
We make a variable that contains the largest value we have seen so far. If the current
number we are looking at is larger, it is the new largest value we have seen so far.

39 40
10/01/21

Counting in a Loop
$ python countloop.py
zork = 0 Before 0

More Loop Patterns…


print('Before', zork) 19
for thing in [9, 41, 12, 3, 74, 15] :
2 41
zork = zork + 1
print(zork, thing) 3 12
print('After', zork) 43
5 74
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.

41 42

Summing in a Loop Finding the Average in a Loop


$ python countloop.py $ python averageloop.py
zork = 0 Before 0 count = 0 Before 0 0
print('Before', zork) 99 sum = 0
for thing in [9, 41, 12, 3, 74, 15] : 199
50 41 print('Before', count, sum)
zork = zork + thing for value in [9, 41, 12, 3, 74, 15] : 2 50 41
print(zork, thing) 62 12 3 62 12
count = count + 1
print('After', zork) 65 3 sum = sum + value 4 65 3
139 74 print(count, sum, value) 5 139 74
154 15 print('After', count, sum, sum / count) 6 154 15
After 154 After 6 154 25.666

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

Filtering in a Loop Search Using a Boolean Variable


$ python search1.py
found = False
Before False
print('Before') $ python search1.py False 9
for value in [9, 41, 12, 3, 74, 15] : print('Before', found)
Before False 41
if value > 20: for value in [9, 41, 12, 3, 74, 15] :
Large number 41 if value == 3 : False 12
print('Large number',value)
print('After')
Large number 74 found = True True 3
After print(found, value) True 74
print('After', found)
True 15
After True
We use an if statement in the loop to catch / filter the If we just want to search and know if a value was found, we use a variable that
values we are looking for. starts at False and is set to True as soon as we find what we are looking for.

45 46

How to Find the Smallest Value Finding the Smallest Value


$ python largest.py
largest_so_far = -1 smallest_so_far = -1
Before -1
print('Before', largest_so_far) print('Before', smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15] : 9 9 for the_num in [9, 41, 12, 3, 74, 15] :
if the_num > largest_so_far : 41 41 if the_num < smallest_so_far :
largest_so_far = the_num 41 12 smallest_so_far = the_num
print(largest_so_far, the_num) 41 3 print(smallest_so_far, the_num)
74 74
print('After', largest_so_far) 74 15 print('After', smallest_so_far)
After 74

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

Finding the Smallest Value Finding the Smallest Value


$ python smallbad.py smallest = None $ python smallest.py
smallest_so_far = -1
Before -1 print('Before') Before
print('Before', smallest_so_far) for value in [9, 41, 12, 3, 74, 15] :
for the_num in [9, 41, 12, 3, 74, 15] : -1 9 99
-1 41 if smallest is None :
if the_num < smallest_so_far : 9 41
smallest = value
smallest_so_far = the_num -1 12 9 12
elif value < smallest :
print(smallest_so_far, the_num) -1 3 smallest = value 33
-1 74 print(smallest, value) 3 74
print('After', smallest_so_far) -1 15 print('After', smallest) 3 15
After -1 After 3

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

The is and is not Operators Summary


• Python has an is operator • While loops (indefinite) • For loops (definite)
smallest = None that can be used in logical
print('Before') expressions • Infinite loops • Iteration variables
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
• Implies “is the same as” • Using break • Loop idioms
smallest = value
elif value < smallest :
smallest = value • Similar to, but stronger than • Using continue • Largest or smallest
print(smallest, value) ==
• None constants and variables
print('After', smallest)
• is not also is a logical
operator

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.

Initial Development: Charles Severance, University of Michigan


School of Information

… Insert new Contributors and Translators here

53

You might also like