Download Loops in Python (part 1)

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
while
Loops in Python (part 1)
L555
Dept. of Linguistics, Indiana University
Fall 2010
1/9
Loops
Loops in Python
(part 1)
Loops
while
Iteration
Loops allow us to carry out one or more statements
repeatedly.
Syntax:
while < t e s t > :
do . . .
do . . .
2/9
Loops in Python
(part 1)
While
Loops
while
Example
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
I
the body of the loop is executed until the test is false
if the test is false, the next statement after the loop is
executed
I
if the test is false form the beginning, the body of the
loop is not executed at all
3/9
While
Loops in Python
(part 1)
Loops
while
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.
4/9
Common Errors
Loops in Python
(part 1)
Loops
while
Forgetting to advance your control variable
Make sure that the variable involved in the test changes in
the body of the loop.
Example
mycount = 1
while mycount <= 100:
p r i n t mycount
5/9
Common Errors
Loops in Python
(part 1)
Loops
while
Wrong incrementing
If you want to decrement, make sure that you do not
automatically increment
Example
mycount = 100
while mycount > 0 :
p r i n t mycount
mycount += 1
6/9
Common Errors
Loops in Python
(part 1)
Loops
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.
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 #1: iteration
Loops in Python
(part 1)
Loops
while
As we’ve just seen, while loops can be used to iterate over
a sequence.
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
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