SlideShare a Scribd company logo
1 of 10
Download to read offline
Loops and Iteration
Chapter 5
Python for Informatics: Exploring Information
www.pythonlearn.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- Charles Severance
Repeated Steps
Output:
5
4
3
2
1
Blastoff!
0
Program:
n = 5
while n > 0 :
print n
n = n - 1
print 'Blastoff!'
print n
n > 0 ?
n = 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 'Blastoff'
Yes
n = 5
print n
An Infinite Loop
n = 5
while n > 0 :
print 'Lather'
print 'Rinse'
print 'Dry off!'
n > 0 ?
No
print 'Dry off!'
Yes
n = 5
print 'Lather'
print 'Rinse'
What is wrong with this loop?
Another Loop
n = 0
while n > 0 :
print 'Lather'
print 'Rinse'
print 'Dry off!'
n > 0 ?
No
print 'Dry off!'
Yes
n = 0
print 'Lather'
print 'Rinse'
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:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
> hello there
hello there
> finished
finished
> 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:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
> hello there
hello there
> finished
finished
> done
Done!
True ?
No
print 'Done'
Yes
....
...
break
while True:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
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 line
print 'Done!'
> hello there
hello there
> # don't print this
> print this!
print this!
> done
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:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!
True ?
No
print 'Done'
Yes
....
...
while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
....
...
continue
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"
A Simple Definite Loop
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
5
4
3
2
1
Blastoff!
A Simple Definite Loop
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print 'Happy NewYear:', friend
print 'Done!'
Happy NewYear: Joseph
Happy NewYear: Glenn
Happy NewYear: Sally
Done!
A Simple Definite Loop
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
5
4
3
2
1
Blastoff!
Done?
Yes
print 'Blast off!'
print i
No
Move 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.
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
Done?
Yes
print i
No
Move 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
sequence
for i in [5, 4, 3, 2, 1] :
print i
Done?
Yes
print i
No
Move i ahead
print i
i = 5
print i
i = 4
print i
i = 3
print i
i = 2
print i
i = 1
for i in [5, 4, 3, 2, 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
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 initial
values
Look for something or
do something to each
entry separately,
updating a variable.
for thing in data:
Look at the variables.
Looping through a Set
print 'Before'
for thing in [9, 41, 12, 3, 74, 15] :
print thing
print 'After'
$ python basicloop.py
Before
9
41
12
3
74
15
After
9 41 12 3 74 15
What is the Largest Number?
9 41 12 3 74 15
What is the Largest Number?
largest_so_far -19 41 74
Finding the largest value
largest_so_far = -1
print 'Before', largest_so_far
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num > largest_so_far :
largest_so_far = the_num
print largest_so_far, the_num
print 'After', largest_so_far
$ python largest.py
Before -1
9 9
41 41
41 12
41 3
74 74
74 15
After 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.
Counting in a Loop
zork = 0
print 'Before', zork
for thing in [9, 41, 12, 3, 74, 15] :
zork = zork + 1
print zork, thing
print 'After', zork
$ python countloop.py
Before 0
1 9
2 41
3 12
4 3
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
print 'Before', zork
for thing in [9, 41, 12, 3, 74, 15] :
zork = zork + thing
print zork, thing
print 'After', zork
$ python countloop.py
Before 0
9 9
50 41
62 12
65 3
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
sum = 0
print 'Before', count, sum
for value in [9, 41, 12, 3, 74, 15] :
count = count + 1
sum = sum + value
print count, sum, value
print 'After', count, sum, sum / count
$ python averageloop.py
Before 0 0
1 9 9
2 50 41
3 62 12
4 65 3
5 139 74
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'
for value in [9, 41, 12, 3, 74, 15] :
if value > 20:
! print 'Large number',value
print 'After'
$ python search1.py
Before
Large number 41
Large number 74
After
We use an if statement in the loop to catch / filter the
values we are looking for.
Search Using a BooleanVariable
found = False
print 'Before', found
for value in [9, 41, 12, 3, 74, 15] :
if value == 3 :
found = True
print found, value
print 'After', found
$ python search1.py
Before False
False 9
False 41
False 12
True 3
True 74
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_so_far = -1
print 'Before', largest_so_far
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num > largest_so_far :
largest_so_far = the_num
print largest_so_far, the_num
print 'After', largest_so_far
$ python largest.py
Before -1
9 9
41 41
41 12
41 3
74 74
74 15
After 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.
Finding the smallest value?
smallest = -1
print 'Before', smallest
for value in [9, 41, 12, 3, 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_so_far = -1
print 'Before', smallest_so_far
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print smallest_so_far, the_num
print 'After', smallest_so_far
We make a variable that contains the smallest value we have seen so far. If the
current number we are looking at is smaller, it is the new smallest value we
have seen so far.
9 41 12 3 74 15
What is the Smallest Number?
smallest_so_far -1
Finding the smallest value
smallest_so_far = -1
print 'Before', smallest_so_far
for the_num in [3, 41, 12, 9, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print smallest_so_far, the_num
print 'After', smallest_so_far
We make a variable that contains the smallest value we have seen so far. If the
current number we are looking at is smaller, it is the new smallest value we
have seen so far.
$ python largest.py
Before -1
-1 3
-1 41
-1 12
-1 9
-1 74
-1 15
After -1
Finding the smallest value
smallest = None
print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
if smallest is None :
smallest = value
elif value < smallest :
smallest = value
print smallest, value
print 'After', smallest
$ python smallest.py
Before
9 9
9 41
9 12
3 3
3 74
3 15
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
• 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 = 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
Summary
• While loops (indefinite)
• Infinite loops
• Using break
• Using continue
• For loops (definite)
• Iteration variables
• Counting in loops
• Summing in loops
• Averaging in loops
• Searching in loops
• Detecting in loops
• Largest or smallest

More Related Content

Similar to Py4Inf-05-Iterations-Print.pdf

Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
jamvantsolanki
 
Programming with python
Programming with pythonProgramming with python
Programming with python
sarogarage
 
Python+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdfPython+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdf
Ganteng tengab
 

Similar to Py4Inf-05-Iterations-Print.pdf (20)

While loop
While loopWhile loop
While loop
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Introduction to c part -1
Introduction to c   part -1Introduction to c   part -1
Introduction to c part -1
 
L06
L06L06
L06
 
Programming with python
Programming with pythonProgramming with python
Programming with python
 
Chapter06.PPT
Chapter06.PPTChapter06.PPT
Chapter06.PPT
 
Init() Lesson 3
Init() Lesson 3Init() Lesson 3
Init() Lesson 3
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_Statement
 
Pythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxPythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptx
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Python+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdfPython+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdf
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
06 Loops
06 Loops06 Loops
06 Loops
 
Python Control Structures.pptx
Python Control Structures.pptxPython Control Structures.pptx
Python Control Structures.pptx
 

Recently uploaded

Seizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networksSeizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networks
IJECEIAES
 

Recently uploaded (20)

Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
Filters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsFilters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility Applications
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
handbook on reinforce concrete and detailing
handbook on reinforce concrete and detailinghandbook on reinforce concrete and detailing
handbook on reinforce concrete and detailing
 
15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon15-Minute City: A Completely New Horizon
15-Minute City: A Completely New Horizon
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
History of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationHistory of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & Modernization
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptx
 
Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...
 
Artificial Intelligence in due diligence
Artificial Intelligence in due diligenceArtificial Intelligence in due diligence
Artificial Intelligence in due diligence
 
Dynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptxDynamo Scripts for Task IDs and Space Naming.pptx
Dynamo Scripts for Task IDs and Space Naming.pptx
 
Interfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdfInterfacing Analog to Digital Data Converters ee3404.pdf
Interfacing Analog to Digital Data Converters ee3404.pdf
 
Seizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networksSeizure stage detection of epileptic seizure using convolutional neural networks
Seizure stage detection of epileptic seizure using convolutional neural networks
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptx
 
Intro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney UniIntro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney Uni
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 

Py4Inf-05-Iterations-Print.pdf

  • 1. Loops and Iteration Chapter 5 Python for Informatics: Exploring Information www.pythonlearn.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- Charles Severance Repeated Steps Output: 5 4 3 2 1 Blastoff! 0 Program: n = 5 while n > 0 : print n n = n - 1 print 'Blastoff!' print n n > 0 ? n = 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 'Blastoff' Yes n = 5 print n An Infinite Loop n = 5 while n > 0 : print 'Lather' print 'Rinse' print 'Dry off!' n > 0 ? No print 'Dry off!' Yes n = 5 print 'Lather' print 'Rinse' What is wrong with this loop?
  • 2. Another Loop n = 0 while n > 0 : print 'Lather' print 'Rinse' print 'Dry off!' n > 0 ? No print 'Dry off!' Yes n = 0 print 'Lather' print 'Rinse' 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: line = raw_input('> ') if line == 'done' : break print line print 'Done!' > hello there hello there > finished finished > 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: line = raw_input('> ') if line == 'done' : break print line print 'Done!' > hello there hello there > finished finished > done Done! True ? No print 'Done' Yes .... ... break while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
  • 3. 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 line print 'Done!' > hello there hello there > # don't print this > print this! print this! > done 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: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' > hello there hello there > # don't print this > print this! print this! > done Done! True ? No print 'Done' Yes .... ... while True: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' .... ... continue 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
  • 4. 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 for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff! A Simple Definite Loop friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy NewYear:', friend print 'Done!' Happy NewYear: Joseph Happy NewYear: Glenn Happy NewYear: Sally Done! A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff! Done? Yes print 'Blast off!' print i No Move 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.
  • 5. 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 Done? Yes print i No Move 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 sequence for i in [5, 4, 3, 2, 1] : print i Done? Yes print i No Move i ahead print i i = 5 print i i = 4 print i i = 3 print i i = 2 print i i = 1 for i in [5, 4, 3, 2, 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"
  • 6. Loop Idioms What We Do in Loops Note: Even though these examples are simple, the patterns apply to all kinds of loops 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 initial values Look for something or do something to each entry separately, updating a variable. for thing in data: Look at the variables. Looping through a Set print 'Before' for thing in [9, 41, 12, 3, 74, 15] : print thing print 'After' $ python basicloop.py Before 9 41 12 3 74 15 After 9 41 12 3 74 15 What is the Largest Number?
  • 7. 9 41 12 3 74 15 What is the Largest Number? largest_so_far -19 41 74 Finding the largest value largest_so_far = -1 print 'Before', largest_so_far for the_num in [9, 41, 12, 3, 74, 15] : if the_num > largest_so_far : largest_so_far = the_num print largest_so_far, the_num print 'After', largest_so_far $ python largest.py Before -1 9 9 41 41 41 12 41 3 74 74 74 15 After 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. Counting in a Loop zork = 0 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + 1 print zork, thing print 'After', zork $ python countloop.py Before 0 1 9 2 41 3 12 4 3 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 print 'Before', zork for thing in [9, 41, 12, 3, 74, 15] : zork = zork + thing print zork, thing print 'After', zork $ python countloop.py Before 0 9 9 50 41 62 12 65 3 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.
  • 8. Finding the Average in a Loop count = 0 sum = 0 print 'Before', count, sum for value in [9, 41, 12, 3, 74, 15] : count = count + 1 sum = sum + value print count, sum, value print 'After', count, sum, sum / count $ python averageloop.py Before 0 0 1 9 9 2 50 41 3 62 12 4 65 3 5 139 74 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' for value in [9, 41, 12, 3, 74, 15] : if value > 20: ! print 'Large number',value print 'After' $ python search1.py Before Large number 41 Large number 74 After We use an if statement in the loop to catch / filter the values we are looking for. Search Using a BooleanVariable found = False print 'Before', found for value in [9, 41, 12, 3, 74, 15] : if value == 3 : found = True print found, value print 'After', found $ python search1.py Before False False 9 False 41 False 12 True 3 True 74 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_so_far = -1 print 'Before', largest_so_far for the_num in [9, 41, 12, 3, 74, 15] : if the_num > largest_so_far : largest_so_far = the_num print largest_so_far, the_num print 'After', largest_so_far $ python largest.py Before -1 9 9 41 41 41 12 41 3 74 74 74 15 After 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.
  • 9. Finding the smallest value? smallest = -1 print 'Before', smallest for value in [9, 41, 12, 3, 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_so_far = -1 print 'Before', smallest_so_far for the_num in [9, 41, 12, 3, 74, 15] : if the_num < smallest_so_far : smallest_so_far = the_num print smallest_so_far, the_num print 'After', smallest_so_far We make a variable that contains the smallest value we have seen so far. If the current number we are looking at is smaller, it is the new smallest value we have seen so far. 9 41 12 3 74 15 What is the Smallest Number? smallest_so_far -1 Finding the smallest value smallest_so_far = -1 print 'Before', smallest_so_far for the_num in [3, 41, 12, 9, 74, 15] : if the_num < smallest_so_far : smallest_so_far = the_num print smallest_so_far, the_num print 'After', smallest_so_far We make a variable that contains the smallest value we have seen so far. If the current number we are looking at is smaller, it is the new smallest value we have seen so far. $ python largest.py Before -1 -1 3 -1 41 -1 12 -1 9 -1 74 -1 15 After -1
  • 10. Finding the smallest value smallest = None print 'Before' for value in [9, 41, 12, 3, 74, 15] : if smallest is None : smallest = value elif value < smallest : smallest = value print smallest, value print 'After', smallest $ python smallest.py Before 9 9 9 41 9 12 3 3 3 74 3 15 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 • 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 = 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 Summary • While loops (indefinite) • Infinite loops • Using break • Using continue • For loops (definite) • Iteration variables • Counting in loops • Summing in loops • Averaging in loops • Searching in loops • Detecting in loops • Largest or smallest