Download Loops in Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Loops in Python
(part 1)
Loops
Loops
Loops in Python
(part 1)
Loops
while
while
Iteration
Loops allow us to carry out one or more statements
repeatedly.
Loops in Python (part 1)
L555
Syntax:
Dept. of Linguistics, Indiana University
Fall 2010
while < t e s t > :
do . . .
do . . .
1/9
While
Loops in Python
(part 1)
2/9
While
Loops
Example
Loops
while
while
mycount = 1
while mycount <= 100:
p r i n t mycount
mycount += 1
I
the test is executed first, and if it is positive, the body of
the loop is executed
I
if the test is false, the next statement after the loop is
executed
I
I
Loops in Python
(part 1)
Beware of infinite loops!
It is easy to create infinite loops with while. Make sure that
your while condition will return false at some point.
the body of the loop is executed until the test is false
if the test is false form the beginning, the body of the
loop is not executed at all
3/9
Common Errors
Loops in Python
(part 1)
4/9
Common Errors
Loops
Loops in Python
(part 1)
Loops
while
while
Wrong incrementing
Forgetting to advance your control variable
If you want to decrement, make sure that you do not
automatically increment
Make sure that the variable involved in the test changes in
the body of the loop.
Example
Example
mycount = 100
while mycount > 0 :
p r i n t mycount
mycount += 1
mycount = 1
while mycount <= 100:
p r i n t mycount
5/9
6/9
Common Errors
Loops in Python
(part 1)
Use #1: iteration
Loops
Loops in Python
(part 1)
Loops
while
while
Off-by-1 errors
Getting the beginning and the end of a loop right can be
tricky: Should it start with 0 or 1? And remember that the
control variable is incremented before the loop is finished.
As we’ve just seen, while loops can be used to iterate over
a sequence.
Example
p r i n t ’ m u l t i p l e s o f 33 ’
mycount = 0
while mycount <= 100:
mycount += 33
p r i n t mycount
p r i n t ’ T h i s i s t h e end : ’ + s t r ( mycount )
7/9
Use #2: until
Loops in Python
(part 1)
Loops
while
Another, subtly different use is to perform the same actions
until a certain condition is reached.
Example
user input = ” ”
while l e n ( u s e r i n p u t ) < 3 :
u s e r i n p u t = r a w i n p u t ( ’ Please e n t e r l o n g s t r i n g :
’)
p r i n t ” Thank you f o r e n t e r i n g a l o n g enough s t r i n g ! ”
9/9
I
Commonly done by iterating over integers: integers
easily count how many times you do something.
I
You can change the way you iterate: i += 2, i -= 1,
...
8/9