SlideShare a Scribd company logo
Loops and Iteration
Chapter 5
Python for Everybody
www.py4e.com
Repeated Steps
Program:
n = 5
while n > 0 :
print(n)
n = n – 1
print('Blastoff!')
print(n)
n > 0 ?
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)
Output:
5
4
3
2
1
Blastoff!
0
n = n -1
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 is this loop doing?
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
> hello there
hello there
> finished
finished
> done
Done!
while True:
line = input('> ')
if line == 'done' :
break
print(line)
print('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
> hello there
hello there
> finished
finished
> done
Done!
while True:
line = input('> ')
if line == 'done' :
break
print(line)
print('Done!')
True ?
No
print('Done')
Yes
....
...
while True:
line = input('> ')
if line == 'done' :
break
print(line)
print('Done!')
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
break
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 = 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 = 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
Iterating over a set of items…
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?
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” through 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”
through 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)
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)
Done?
Yes
print(i)
No
Move i ahead
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
What is the Largest Number?
3
What is the Largest Number?
What is the Largest Number?
41
What is the Largest Number?
12
What is the Largest Number?
9
What is the Largest Number?
74
What is the Largest Number?
15
What is the Largest Number?
3
What is the Largest Number?
41 12 9 74 15
What is the Largest Number?
largest_so_far -1
3
What is the Largest Number?
largest_so_far 3
What is the Largest Number?
41
largest_so_far 41
What is the Largest Number?
12
largest_so_far 41
What is the Largest Number?
9
largest_so_far 41
What is the Largest Number?
74
largest_so_far 74
What is the Largest Number?
15
74
3
What is the Largest Number?
41 12 9 74 15
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.
More Loop Patterns…
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.666
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 Boolean Variable
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.
How to Find the Smallest 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
How would we change this to make it find the smallest value in the list?
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 switched the variable name to smallest_so_far and switched the > to <
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 switched the variable name to smallest_so_far and switched the > to <
$ python smallbad.py
Before -1
-1 9
-1 41
-1 12
-1 3
-1 74
-1 15
After -1
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.
Finding the Smallest Value
The is and is not Operators
• Python has an is operator
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
• None constants and variables
• For loops (definite)
• Iteration variables
• Loop idioms
• Largest or smallest
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
...

More Related Content

PPTX
High PR PPT submission sites generally allow you to add backlinks
PDF
Py4Inf-05-Iterations-Print.pdf
PPT
Py4inf 05-iterations (1)
PPT
Py4inf 05-iterations (1)
PPT
Py4inf 05-iterations
PPTX
Python Lecture 5
PDF
LOOPS TOPIC FOR CLASS XI PYTHON SYLLABUS
PPTX
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
High PR PPT submission sites generally allow you to add backlinks
Py4Inf-05-Iterations-Print.pdf
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
Py4inf 05-iterations
Python Lecture 5
LOOPS TOPIC FOR CLASS XI PYTHON SYLLABUS
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON

Similar to Learn various loops and Iterations in Python (20)

PPTX
Iteration
PPTX
Lexture about strings, all examples and theoretical part is included
PDF
2 Python Basics II meeting 2 tunghai university pdf
PPT
Python Programming Introduction - Loops & Boolean
PDF
Notes2
PPTX
PPT
(Data Structure) Chapter11 searching & sorting
PPTX
1. control structures in the python.pptx
PPT
12 lec 12 loop
PPT
Chapter 11 - Sorting and Searching
PPTX
3.2 looping statement
PPTX
PPTX
Python_Loops.pptxpython loopspython loopspython loopspython loopspython loops...
PPTX
Pythonlearn-03-Conditional.pptx
PDF
Python for High School Programmers
PPTX
TN 12 computer Science - ppt CHAPTER-6.pptx
PDF
Python_Module_2.pdf
DOCX
Python unit 3 and Unit 4
PPTX
Python-Dictionaries.pptx easy way to learn dictionaries
Iteration
Lexture about strings, all examples and theoretical part is included
2 Python Basics II meeting 2 tunghai university pdf
Python Programming Introduction - Loops & Boolean
Notes2
(Data Structure) Chapter11 searching & sorting
1. control structures in the python.pptx
12 lec 12 loop
Chapter 11 - Sorting and Searching
3.2 looping statement
Python_Loops.pptxpython loopspython loopspython loopspython loopspython loops...
Pythonlearn-03-Conditional.pptx
Python for High School Programmers
TN 12 computer Science - ppt CHAPTER-6.pptx
Python_Module_2.pdf
Python unit 3 and Unit 4
Python-Dictionaries.pptx easy way to learn dictionaries
Ad

More from coreyanderson7866 (6)

PPTX
2-The unified process in computer Science.pptx
PDF
Cloud and Grid Computing PPT computer science.pdf
PDF
DS-Visualization-Unit-4 COMPUTER SCIENCE.pdf
PPTX
Presentation_ON _HTML Irfan Rashid .pptx
PPTX
Contingency arguments for Existence Of Allah.edd.pptx
PDF
Microbiology report card test smims .pdf
2-The unified process in computer Science.pptx
Cloud and Grid Computing PPT computer science.pdf
DS-Visualization-Unit-4 COMPUTER SCIENCE.pdf
Presentation_ON _HTML Irfan Rashid .pptx
Contingency arguments for Existence Of Allah.edd.pptx
Microbiology report card test smims .pdf
Ad

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation theory and applications.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Electronic commerce courselecture one. Pdf
Approach and Philosophy of On baking technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The AUB Centre for AI in Media Proposal.docx
Network Security Unit 5.pdf for BCA BBA.
Mobile App Security Testing_ A Comprehensive Guide.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Empathic Computing: Creating Shared Understanding
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
sap open course for s4hana steps from ECC to s4
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation theory and applications.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
MIND Revenue Release Quarter 2 2025 Press Release
Programs and apps: productivity, graphics, security and other tools
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Encapsulation_ Review paper, used for researhc scholars
Electronic commerce courselecture one. Pdf

Learn various loops and Iterations in Python

  • 1. Loops and Iteration Chapter 5 Python for Everybody www.py4e.com
  • 2. Repeated Steps Program: n = 5 while n > 0 : print(n) n = n – 1 print('Blastoff!') print(n) n > 0 ? 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) Output: 5 4 3 2 1 Blastoff! 0 n = n -1
  • 3. 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?
  • 4. 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 is this loop doing?
  • 5. 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 > hello there hello there > finished finished > done Done! while True: line = input('> ') if line == 'done' : break print(line) print('Done!')
  • 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 > hello there hello there > finished finished > done Done! while True: line = input('> ') if line == 'done' : break print(line) print('Done!')
  • 7. True ? No print('Done') Yes .... ... while True: line = input('> ') if line == 'done' : break print(line) print('Done!') http://en.wikipedia.org/wiki/Transporter_(Star_Trek) break
  • 8. 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 = 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!
  • 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 = 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. True ? No print('Done') Yes while True: line = raw_input('> ') if line[0] == '#' : continue if line == 'done' : break print(line) print('Done!') ... .... continue
  • 11. 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
  • 12. Definite Loops Iterating over a set of items…
  • 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? 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.
  • 17. Looking at in... • The iteration variable “iterates” through 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? Yes print(i) No Move i ahead • The iteration variable “iterates” through 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)
  • 19. 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) Done? Yes print(i) No Move i ahead
  • 20. Loop Idioms: What We Do in Loops Note: Even though these examples are simple, the patterns apply to all kinds of loops
  • 21. 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
  • 22. 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
  • 23. What is the Largest Number?
  • 24. 3 What is the Largest Number?
  • 25. What is the Largest Number? 41
  • 26. What is the Largest Number? 12
  • 27. What is the Largest Number? 9
  • 28. What is the Largest Number? 74
  • 29. What is the Largest Number? 15
  • 30. What is the Largest Number?
  • 31. 3 What is the Largest Number? 41 12 9 74 15
  • 32. What is the Largest Number? largest_so_far -1
  • 33. 3 What is the Largest Number? largest_so_far 3
  • 34. What is the Largest Number? 41 largest_so_far 41
  • 35. What is the Largest Number? 12 largest_so_far 41
  • 36. What is the Largest Number? 9 largest_so_far 41
  • 37. What is the Largest Number? 74 largest_so_far 74
  • 38. What is the Largest Number? 15 74
  • 39. 3 What is the Largest Number? 41 12 9 74 15 74
  • 40. 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.
  • 42. 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.
  • 43. 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.
  • 44. 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.666 An average just combines the counting and sum patterns and divides when the loop is done.
  • 45. 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.
  • 46. Search Using a Boolean Variable 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.
  • 47. How to Find the Smallest 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 How would we change this to make it find the smallest value in the list?
  • 48. 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 switched the variable name to smallest_so_far and switched the > to <
  • 49. 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 switched the variable name to smallest_so_far and switched the > to < $ python smallbad.py Before -1 -1 9 -1 41 -1 12 -1 3 -1 74 -1 15 After -1
  • 50. 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. Finding the Smallest Value
  • 51. The is and is not Operators • Python has an is operator 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)
  • 52. Summary • While loops (indefinite) • Infinite loops • Using break • Using continue • None constants and variables • For loops (definite) • Iteration variables • Loop idioms • Largest or smallest
  • 53. 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 ...

Editor's Notes

  • #1: Note from Chuck. If you are using these materials, you can remove the UM logo and replace it with your own, but please retain the CC-BY logo on the first page as well as retain the acknowledgement page(s) at the end.