Top Banner
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information www.pythonlearn.com
39

Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Dec 24, 2015

Download

Documents

Milton Wilcox
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Loops and IterationChapter 5

Python for Informatics: Exploring Informationwww.pythonlearn.com

Page 2: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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- Charles Severance

Page 3: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Repeated StepsOutput:

54321Blastoff! 0

Program:

n = 5while n > 0 : print n n = n – 1print 'Blastoff!'print n

n > 0 ?n > 0 ?

n = n -1n = n -1

Loops (repeated steps) have iteration variables that change each time through a

loop. Often these iteration variables go through a sequence of numbers.

No

print print 'Blastoff''Blastoff'

Yes

n = 5n = 5

print print nn

Page 4: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

An Infinite Loop

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

n > 0 ?n > 0 ?No

print 'Dry print 'Dry off!'off!'

Yes

n = 5n = 5

print print 'Lather''Lather'

print print 'Rinse''Rinse'

What is wrong with this loop?

Page 5: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Another Loop

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

n > 0 ?n > 0 ?No

print 'Dry print 'Dry off!'off!'

Yes

n = 0n = 0

print print 'Lather''Lather'

print print 'Rinse''Rinse'

What does this loop do?

Page 6: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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

> hello therehello there> finishedfinished> doneDone!

Page 7: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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

> hello therehello there> finishedFinished> doneDone!

Page 8: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

True ?True ?No

print 'Done'print 'Done'

Yes

........

......

breakbreak

while True: line = raw_input('> ') if line == 'done' : break print lineprint 'Done!'

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

Page 9: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print lineprint 'Done!'

> hello therehello there> # don't print this> print this!print this!> doneDone!

Page 10: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print lineprint 'Done!'

> hello therehello there> # don't print this> print this!print this!> doneDone!

Page 11: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

True ?True ?No

print 'Done'print 'Done'

Yes

........

......

while True: line = raw_input('> ’) if line[0] == '#' : continue if line == 'done' : break print lineprint 'Done!'

........

......

continuecontinue

Page 12: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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

Page 13: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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"

Page 14: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

A Simple Definite Loop

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

54321Blastoff!

Page 15: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

A Definite Loop with Strings

friends = ['Joseph', 'Glenn', 'Sally']for friend in friends : print 'Happy New Year:', friendprint 'Done!'

Happy New Year: JosephHappy New Year: GlennHappy New Year: SallyDone!

Page 16: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

A Simple Definite Loop

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

54321Blastoff!

Done?Done?Yes

print 'Blast print 'Blast off!'off!'

print print ii

No

Move i aheadMove i ahead

Definite loops (for loops) have explicit iteration variables that change each time through a loop. These iteration variables

move through the sequence or set.

Page 17: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Looking at In...•The iteration variable

“iterates” though the sequence (ordered set)

•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 sequence

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

Iteration variable

Five-element sequence

Page 18: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Done?Done?Yes

print print ii

No

Move i aheadMove i ahead•The iteration variable

“iterates” though the sequence (ordered set)

•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 sequencefor i in [5, 4, 3, 2, 1]

: print i

Page 19: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Done?Done?Yes

print print ii

No

Move i aheadMove i ahead

print print ii

i = 5i = 5

print print ii

i = 4i = 4

print print ii

i = 3i = 3

print print ii

i = 2i = 2

print print ii

i = 1i = 1

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

Page 20: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

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"

Page 21: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Loop IdiomsWhat We Do in Loops

Note: Even though these examples are simple, the patterns apply to all kinds of

loops

Page 22: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Making “smart” loops

•The trick is “knowing” something about the whole loop when you are stuck writing code that only sees one entry at a time

Set some variables to Set some variables to initial valuesinitial values

Look for something Look for something or do something to or do something to

each entry each entry separately, updating separately, updating

a variable.a variable.

for thing in data:

Look at the variables.Look at the variables.

Page 23: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Looping through a Set

print 'Before'for thing in [9, 41, 12, 3, 74, 15] : print thingprint 'After'

$ python basicloop.pyBefore9411237415After

Page 24: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

What is the Largest Number?

Page 25: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

3

What is the Largest Number?

largest_so_far -134174

41

12

974

15

Page 26: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .
Page 27: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Counting in a Loopzork = 0print 'Before', zorkfor thing in [9, 41, 12, 3, 74, 15] : zork = zork + 1 print zork, thingprint 'After', zork

$ python countloop.pyBefore 01 92 413 124 35 746 15After 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.

Page 28: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Summing in a Loopzork = 0print 'Before', zorkfor thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print zork, thingprint 'After', zork

$ python countloop.py Before 09 950 4162 1265 3139 74154 15After 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.

Page 29: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Finding the Average in a Loop

count = 0sum = 0print 'Before', count, sumfor value in [9, 41, 12, 3, 74, 15] : count = count + 1 sum = sum + value print count, sum, valueprint 'After', count, sum, sum / count

$ python averageloop.py Before 0 01 9 92 50 413 62 124 65 35 139 746 154 15After 6 154 25

An average just combines the counting and sum patterns and divides when the loop is

done.

Page 30: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Filtering in a Loop

print 'Before’for value in [9, 41, 12, 3, 74, 15] : if value > 20: print 'Large number',valueprint 'After'

$ python search1.py BeforeLarge number 41Large number 74After

We use an if statement in the loop to catch / filter the values we are looking for.

Page 31: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Search Using a Boolean Variable

found = Falseprint 'Before', foundfor value in [9, 41, 12, 3, 74, 15] : if value == 3 : found = True print found, valueprint 'After', found

$ python search1.py Before FalseFalse 9False 41False 12True 3True 74True 15After 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.

Page 32: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

What is the Smallest Number?

Page 33: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

9

What is the Smallest Number?

smallest_so_far -1

41

12

374

15

Page 34: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .
Page 35: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

9

What is the Smallest Number?

largest_so_far None93

41

12

374

15

Page 36: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .
Page 37: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Finding the smallest value

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

$ python smallest.py Before9 99 419 123 33 743 15After 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.

Page 38: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

The "is" and "is not" Operators

•Python has an "is" operaror 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 = Noneprint 'Before’for value in [3, 41, 12, 9, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, valueprint 'After', smallest

Page 39: Loops and Iteration Chapter 5 Python for Informatics: Exploring Information .

Summary• While loops (indefinite)

• Infinite loops

• Using break

• Using continue

• For loops (definite)

• Iteration variables

• Largest or smallest