0% found this document useful (0 votes)
28 views

Py4Inf 05 Iterations

The document discusses loops and iteration in Python. It covers while loops, for loops, and how to use break and continue statements to control loop behavior. It also distinguishes between indefinite and definite loops.

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Py4Inf 05 Iterations

The document discusses loops and iteration in Python. It covers while loops, for loops, and how to use break and continue statements to control loop behavior. It also distinguishes between indefinite and definite loops.

Uploaded by

junedijoasli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Loops and Iteration

Chapter 5

Python for Informatics: Exploring Information


www.py4inf.com
Unless otherwise noted, the content of this course material is licensed under a Creative
Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/.

Copyright 2010, 2011, Charles Severance


n=5
Repeated Steps
No Yes
n>0? Output:
Program:
print n 5
n=5
4
while n > 0 :
3
n = n -1 print n
2
n=n-1
1
print 'Blastoff!'
Blastoff!
print 'Blastoff'
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?
n=5
print 'Lather' while n > 0 :
print 'Lather'
print 'Rinse' print 'Rinse'

print 'Dry off!'

print 'Dry off!'

What is wrong with this loop?


n=0
Another Loop
No Yes
n>0?
n=0
print 'Lather' while n > 0 :
print 'Lather'
print 'Rinse' print 'Rinse'

print 'Dry off!'

print 'Dry off!'


What does this loop do?
Breaking Out of a 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: > hello there


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


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

...

http://en.wikipedia.org/wiki/Transporter_(Star_Trek) print 'Done'


Finishing an Iteration with continue
• The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration

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

while True:
> hello there
line = raw_input('> ')
hello there
if line[0] == '#' :
> # don't print this
continue
> print this!
if line == 'done' :
print this!
break
> done
print line
Done!
print 'Done!'
No
True ? Yes
while True:
line = raw_input('> ') ....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print line
print 'Done!' ...

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


Does this loop terminate?
inp = raw_input('Enter a Number:')
• Collatz Conjecture n = int(inp)
while n != 1 :
python sequence.py print n,
Enter a Number:3 if n % 2 == 0 : # n is even
3 10 5 16 8 4 2 n=n/2
python sequence.py else : # n is odd
Enter a Number:16 n=n*3+1
16 8 4 2
python sequence.py
Enter a Number:50
50 25 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2
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

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

friends = ['Joseph', 'Glenn', 'Sally']

for friend in friends : Happy New Year: Joseph


print 'Happy New Year:', friend Happy New Year: Glenn
Happy New Year: Sally
print 'Done!' Done!
A Simple Definite Loop
No
Yes
Done? Move i ahead 5
for i in [5, 4, 3, 2, 1] : 4
print i 3
print i
2
print 'Blastoff!' 1
Blastoff!

print 'Blast off!'


Definite loops (for loops) have explicit iteration
variables that change each time through a loop. These
iteration variables move through the sequence or set.
Looking at In...
• The iteration variable
“iterates” though the
sequence (ordered set) Five-element sequence
Iteration variable
• The block (body) of code is
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 sequence
No
Yes
Done? Move i ahead • The iteration variable “iterates”
though the sequence (ordered set)
print i • The block (body) of code is
executed once for each value in
the sequence

• The iteration variable moves


through all of the values in the
for i in [5, 4, 3, 2, 1] : sequence
print i
i=5
No print i
Yes
Done? Move i ahead i=4
print i
print i
i=3
print i

i=2
for i in [5, 4, 3, 2, 1] : print i
print i
i=1
print i
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"


Loop Idioms
What We Do in Loops
Note: Even though these examples are simple, the
patterns apply to all kinds of loops
What is the Largest Number?

3 41 12 9 74 15
What is the Largest Number?

3 41 12 9 74 15

largest_so_far -13 41 74
Looping through a Set
$ python basicloop.py
Before
3
print 'Before'
41
for thing in [3, 41, 12, 9, 74, 15] :
12
print thing
9
print 'After'
74
15
After
Finding the largest value
largest = -1 $ python largest.py
print 'Before', largest Before -1
for value in [3, 41, 12, 9, 74, 15] : 33
if value > largest : 41 41
largest = value 41 12
print largest, value 41 9
74 74
print 'After', largest 74 15
After 74

We make a variable that contains the largest value we have seen so far. If the
current value is larger, it becomes the new largest value we have seen so far.
Making “smart” loops
Set some variables to initial
values
for thing in data:
• The trick is “knowing” something
Look for something or
about the whole loop when you
do something to each
are stuck writing code that only
entry separately,
sees one entry at a time updating a variable.

Look at the variables.


Counting in a Loop
zork = 0 $ python countloop.py
print 'Before', zork Before 0
for thing in [3, 41, 12, 9, 74, 15] : 13
zork = zork + 1 2 41
print zork, thing 3 12
print 'After', zork 49
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.
Summing in a Loop
zork = 0 $ python countloop.py
print 'Before', zork Before 0
for thing in [3, 41, 12, 9, 74, 15] : 33
zork = zork + thing 44 41
print zork, thing 56 12
print 'After', zork 65 9
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 $ python averageloop.py
sum = 0 Before 0 0
print 'Before', count, sum 133
for value in [3, 41, 12, 9, 74, 15] : 2 44 41
count = count + 1 3 56 12
sum = sum + value 4 65 9
print count, sum, value 5 139 74
print 'After', count, sum, sum / count 6 154 15
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' $ python search1.py


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

print 'Large number',value Large number 74
print 'After' After

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


values we are looking for.
Search Using a Boolean Variable
found = False $ python search1.py
print 'Before', found Before False
for value in [3, 41, 12, 9, 74, 15] : False 3
if value == 9: False 41
found = True False 12
print found, value True 9
True 74
print 'After', found True 15
After True
If we just want to search and know if a value was found - we use a variable that
starts at False and is set to True as soon as we find what we are looking for.
Finding the largest value
largest = -1 $ python largest.py
print 'Before', largest Before -1
for value in [3, 41, 12, 9, 74, 15] : 33
if value > largest : 41 41
largest = value 41 12
print largest, value 41 9
74 74
print 'After', largest 74 15
After 74

We make a variable that contains the largest value we have seen so far. If the
current value is larger, it becomes the new largest value we have seen so far.
Finding the smallest value?
smallest = -1
print 'Before', smallest
for value in [3, 41, 12, 9, 74, 15] :
if value < smallest :
smallest = value
print smallest, value

print 'After', smallest

We make a variable that contains the smallest value we have seen so far. If the
current value is smaller, it becomes the new smallest value we have seen so far.
What is the Smallest Number?

3 41 12 9 74 15

smallest -1
Finding the smallest value?
smallest = -1
print 'Before', largest
for value in [3, 41, 12, 9, 74, 15] :
if value < smallest :
smallest = value
print smallest, value

print 'After', smallest

We make a variable that contains the smallest value we have seen so far. If the
current value is smaller, it becomes the new smallest value we have seen so far.
Finding the smallest value
smallest = None
print 'Before' $ python smallest.py
for value in [9, 41, 12, 3, 74, 15] : Before
if smallest is None : 99
smallest = value 9 41
elif value < smallest : 9 12
smallest = value 33
print smallest, value 3 74
3 15
print 'After', smallest After 3

We still have a variable that is the smallest so far. The first time through the
loop smallest is None so we take the first value to be the smallest.
The "is" and "is not" Operators
smallest = None
print 'Before' • Python has an "is" operaror that
can be used in logical
for value in [9, 41, 12, 3, 74, 15] :
expressions
if smallest is None :
smallest = value
elif value < smallest : • Implies 'is the same as'
smallest = value
print smallest, value
• Similar to, but stronger than ==

print 'After', smallest


• 'is not' also is a logical operator
Summary
• While loops (indefinite) • Counting in loops

• Infinite loops • Summing in loops

• Using break • Averaging in loops

• Using continue • Searching in loops

• For loops (definite) • Detecting in loops

• Iteration variables • Largest or smallest

You might also like