Loops and Iteration - Open Michigan
[Pages:39]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. .
Copyright 2010- Charles Severance
n = 5
Repeated Steps
No
Yes
n > 0 ?
Program:
Output:
print n
n = 5
5
while n > 0 :
4
n = n -1
print n
n = n ? 1
3
2
print 'Blastoff!'
1
print n
Blastoff!
print 'Blastoff'
0
Loops (repeated steps) have iteration variables that
change each time through a loop. Often these
iteration variables go through a sequence of numbers.
n = 5
No
Yes
n > 0 ?
print 'Lather'
print 'Rinse'
print 'Dry off!'
An Infinite Loop
n = 5
while n > 0 :
print 'Lather'
print 'Rinse'
print 'Dry off!'
What is wrong with this loop?
n = 0
No
Yes
n > 0 ?
print 'Lather'
print 'Rinse'
print 'Dry off!'
Another Loop
n = 0
while n > 0 :
print 'Lather'
print 'Rinse'
print 'Dry off!'
What does this loop do?
Breaking Out of a Loop
? The break statement ends the current loop and jumps to the
statement immediately following the loop
? It is like a loop test that can happen anywhere in the body of the loop
while True:
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!
while True:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
No
True ?
Yes
....
break
...
(Star_Trek)
print 'Done'
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- python tutorial stanford artificial intelligence laboratory
- the zen of python
- programming in python
- python question and answers built in functions
- ©2012 2013 laurent pointal mémento v1 2 2 python 3 cheat
- introduction to python day 1 3
- example true false questions computer science
- loops and iteration open michigan
- conditional execution