|
CS 140: Introduction
to Computer Programming
While Loops
As we have seen, a for
loop is useful for repeating a certain task a
fixed number of times. However, in many
situations it is not known in advance how many
times a particular task should be
performed. For instance, suppose that I
keep asking you to guess my favorite color until
you get it right. Then I ask as long as
your guess does not match the color I have in
mind, which happens to be vermillion. (So
this could take a long time.) The code to
accomplish this looks like
guess = raw_input("Guess my favorite color:
")
while
guess != "vermillion":
print "Nope, not even close."
guess = raw_input("Guess my favorite color
again: ")
As we have become accustomed to, the lines
following the while
statement are indented; these are exactly the
lines that are executed as long as the guess is
incorrect.
If one is not careful, it is entirely possible
to create an endless loop. This occurs
when the condition that a while statement is
checking never actually becomes true. For
instance, a subtle mistake in the above program
would be to give the subsequent guesses a
different name, as in the following code.
guess = raw_input("Guess my favorite color:
")
while
guess != "vermillion":
print "Nope, not even close."
newguess = raw_input("Guess my favorite color
again: ")
Notice that the value of guess
never changes after the first line, so there is
no hope of ever exiting the while loop, even if
the user were lucky enough to eventually type
"vermillion." This observation prompts us
to state the Golden Rule
of While Loops, which is that the body
of the while loop should make it possible
(sooner or later) for the condition being tested
by the while statement to be true.
Here's another scenario in which we wish to
repeat an action over and over, but without
knowing in advance how many times. Let's
add together random two-digit numbers until the
total exceeds 1000, and keep track of how many
tries it takes. (Obviously, this amount
will probably change each time we run the
program.)
import
random
total = 0
tries = 0
while
total <= 1000:
total = total
+ random.randint(10,99)
tries = tries + 1
print "It took", tries, "numbers
to total more than 1000."
Be sure to initialize the variables tries
and total to equal 0 at the
outset, or else Python won't know what to do
when it first encounters them inside the loop.
WARNING: it
is much more difficult to correctly code a while
loop than reading these examples might lead you
to believe. Be sure to get plenty of
practice with this structure!
|
|
|