SlideShare a Scribd company logo
1 of 39
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 > 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 'Blastoff'print 'Blastoff'
Yes
n = 5n = 5
printprint nn
An Infinite Loop
n = 5
while n > 0 :
print 'Lather’
print 'Rinse'
print 'Dry off!'
n > 0 ?n > 0 ?
No
print 'Dry off!'print 'Dry off!'
Yes
n = 5n = 5
printprint 'Lather''Lather'
printprint 'Rinse''Rinse'
What is wrong with this loop?
Another Loop
n = 0
while n > 0 :
print 'Lather’
print 'Rinse'
print 'Dry off!'
n > 0 ?n > 0 ?
No
print 'Dry off!'print 'Dry off!'
Yes
n = 0n = 0
printprint 'Lather''Lather'
printprint 'Rinse''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 ?True ?
No
print 'Done'print 'Done'
Yes
........
......
breakbreak
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 ?True ?
No
print 'Done'print 'Done'
Yes
........
......
while True:
line = raw_input('> ’)
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
........
......
continuecontinue
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 Definite Loop with Strings
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print 'Happy New Year:', friend
print 'Done!'
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: 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?Done?
Yes
print 'Blast off!'print 'Blast off!'
printprint 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.
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?Done?
Yes
printprint 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
Done?Done?
Yes
printprint ii
No
Move i aheadMove i ahead
printprint ii
i = 5i = 5
printprint ii
i = 4i = 4
printprint ii
i = 3i = 3
printprint ii
i = 2i = 2
printprint ii
i = 1i = 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 initialSet some variables to initial
valuesvalues
Look for something orLook for something or
do something to eachdo something to each
entry separately, updatingentry separately, updating
a variable.a variable.
for thing in data:
Look at the variables.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
What is the Largest Number?
3
What is the Largest Number?
largest_so_far -13 41 74
41 12 9 74 15
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.
What is the Smallest Number?
9
What is the Smallest Number?
smallest_so_far -1
41 12 3 74 15
9
What is the Smallest Number?
largest_so_far None 9 3
41 12 3 74 15
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
• Largest or smallest

More Related Content

What's hot (7)

Event Stream Processing with Multiple Threads
Event Stream Processing with Multiple ThreadsEvent Stream Processing with Multiple Threads
Event Stream Processing with Multiple Threads
 
C# loops
C# loopsC# loops
C# loops
 
Strings
StringsStrings
Strings
 
Loop control in c++
Loop control in c++Loop control in c++
Loop control in c++
 
Conditional Loops Python
Conditional Loops PythonConditional Loops Python
Conditional Loops Python
 
Simulador
SimuladorSimulador
Simulador
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
 

Similar to Py4inf 05-iterations (1)

Similar to Py4inf 05-iterations (1) (20)

Py4Inf-05-Iterations-Print.pdf
Py4Inf-05-Iterations-Print.pdfPy4Inf-05-Iterations-Print.pdf
Py4Inf-05-Iterations-Print.pdf
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
 
Notes2
Notes2Notes2
Notes2
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
While loop
While loopWhile loop
While loop
 
python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
 
Programming with python
Programming with pythonProgramming with python
Programming with python
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
Python Loop
Python LoopPython Loop
Python Loop
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Chapter06.PPT
Chapter06.PPTChapter06.PPT
Chapter06.PPT
 
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
 
06 Loops
06 Loops06 Loops
06 Loops
 
Reflex - How does it work?
Reflex - How does it work?Reflex - How does it work?
Reflex - How does it work?
 
Introduction to c part -1
Introduction to c   part -1Introduction to c   part -1
Introduction to c part -1
 
Mastering Python lesson 3a
Mastering Python lesson 3aMastering Python lesson 3a
Mastering Python lesson 3a
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .ppt
 
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
 
Chapter08.pptx
Chapter08.pptxChapter08.pptx
Chapter08.pptx
 

More from karan saini

Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01karan saini
 
Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)karan saini
 
Snrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskySnrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskykaran saini
 
Risc and cisc eugene clewlow
Risc and cisc   eugene clewlowRisc and cisc   eugene clewlow
Risc and cisc eugene clewlowkaran saini
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterationskaran saini
 
Helen keller-1226880485154369-8
Helen keller-1226880485154369-8Helen keller-1226880485154369-8
Helen keller-1226880485154369-8karan saini
 
Final 121114041321-phpapp01
Final 121114041321-phpapp01Final 121114041321-phpapp01
Final 121114041321-phpapp01karan saini
 
Engh 140118084844-phpapp01
Engh 140118084844-phpapp01Engh 140118084844-phpapp01
Engh 140118084844-phpapp01karan saini
 

More from karan saini (20)

Topology ppt
Topology pptTopology ppt
Topology ppt
 
Tibor
TiborTibor
Tibor
 
Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01
 
Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)
 
Snrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskySnrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofsky
 
Science
ScienceScience
Science
 
Risc and cisc eugene clewlow
Risc and cisc   eugene clewlowRisc and cisc   eugene clewlow
Risc and cisc eugene clewlow
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterations
 
Periodic table1
Periodic table1Periodic table1
Periodic table1
 
Maths project
Maths projectMaths project
Maths project
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lcd monitors
Lcd monitorsLcd monitors
Lcd monitors
 
Lab3
Lab3Lab3
Lab3
 
L11cs2110sp13
L11cs2110sp13L11cs2110sp13
L11cs2110sp13
 
Helen keller-1226880485154369-8
Helen keller-1226880485154369-8Helen keller-1226880485154369-8
Helen keller-1226880485154369-8
 
Hardware
HardwareHardware
Hardware
 
Gsm cdma1
Gsm cdma1Gsm cdma1
Gsm cdma1
 
Final 121114041321-phpapp01
Final 121114041321-phpapp01Final 121114041321-phpapp01
Final 121114041321-phpapp01
 
Engh 140118084844-phpapp01
Engh 140118084844-phpapp01Engh 140118084844-phpapp01
Engh 140118084844-phpapp01
 

Recently uploaded

Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Py4inf 05-iterations (1)

  • 1. Loops and Iteration Chapter 5 Python for Informatics: Exploring Information www.pythonlearn.com
  • 2. 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
  • 3. 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 > 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 'Blastoff'print 'Blastoff' Yes n = 5n = 5 printprint nn
  • 4. An Infinite Loop n = 5 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' n > 0 ?n > 0 ? No print 'Dry off!'print 'Dry off!' Yes n = 5n = 5 printprint 'Lather''Lather' printprint 'Rinse''Rinse' What is wrong with this loop?
  • 5. Another Loop n = 0 while n > 0 : print 'Lather’ print 'Rinse' print 'Dry off!' n > 0 ?n > 0 ? No print 'Dry off!'print 'Dry off!' Yes n = 0n = 0 printprint 'Lather''Lather' printprint 'Rinse''Rinse' What does this loop do?
  • 6. 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!
  • 7. 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!
  • 8. True ?True ? No print 'Done'print 'Done' Yes ........ ...... breakbreak while True: line = raw_input('> ') if line == 'done' : break print line print 'Done!' http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
  • 9. 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!
  • 10. 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!
  • 11. True ?True ? No print 'Done'print 'Done' Yes ........ ...... while True: line = raw_input('> ’) if line[0] == '#' : continue if line == 'done' : break print line print 'Done!' ........ ...... continuecontinue
  • 12. 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
  • 13. 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"
  • 14. A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff!
  • 15. A Definite Loop with Strings friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend print 'Done!' Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done!
  • 16. A Simple Definite Loop for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' 5 4 3 2 1 Blastoff! Done?Done? Yes print 'Blast off!'print 'Blast off!' printprint 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.
  • 17. 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
  • 18. Done?Done? Yes printprint 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
  • 19. Done?Done? Yes printprint ii No Move i aheadMove i ahead printprint ii i = 5i = 5 printprint ii i = 4i = 4 printprint ii i = 3i = 3 printprint ii i = 2i = 2 printprint ii i = 1i = 1 for i in [5, 4, 3, 2, 1] : print i
  • 20. 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"
  • 21. Loop Idioms What We Do in Loops Note: Even though these examples are simple, the patterns apply to all kinds of loops
  • 22. 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 initialSet some variables to initial valuesvalues Look for something orLook for something or do something to eachdo something to each entry separately, updatingentry separately, updating a variable.a variable. for thing in data: Look at the variables.Look at the variables.
  • 23. 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
  • 24. What is the Largest Number?
  • 25. 3 What is the Largest Number? largest_so_far -13 41 74 41 12 9 74 15
  • 26.
  • 27. 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.
  • 28. 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.
  • 29. 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.
  • 30. 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.
  • 31. 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.
  • 32. What is the Smallest Number?
  • 33. 9 What is the Smallest Number? smallest_so_far -1 41 12 3 74 15
  • 34.
  • 35. 9 What is the Smallest Number? largest_so_far None 9 3 41 12 3 74 15
  • 36.
  • 37. 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.
  • 38. 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
  • 39. Summary • While loops (indefinite) • Infinite loops • Using break • Using continue • For loops (definite) • Iteration variables • Largest or smallest