the while loop is for repeating a block of code as long as some condition is true. Here is an example:
n = 1
while n <= 3:
print "in loop: n is", n
n = n + 1
print "About to test n (which is ", n , ")"
#end while
print "Loop has terminated. n is", n
It produces the output:
in loop: n is 1
About to test n (which is 2 )
in loop: n is 2
About to test n (which is 3 )
in loop: n is 3
About to test n (which is 4 )
Loop has terminated. n is 4
It is a counting loop, and repeats 3 times.
-
first, we set n to 1
-
now we do the while. The condition is true, so we enter the indented block.
-
We print messages so that we can trace the order of executuin.
-
we add 1 to n.
-
When we hit the bottom of the loop, the program moves back up to the top of the loop, and re-tests n
-
As long as the test is true, the loop executes again. Eventually, it is false, and the program skips
to the line following the end of the loop. Note that we have used a #end while comment. This is optional.
As a picture:
+--> while some condition : -->--+
| | |
| true |
| | |
| block of code... |
| | false
-------------<------ |
|
-------------------+
rest of program
|_ _|
Another way to look at this is that the program is 'trapped' in the loop, and can only drop through
to the rest of the program when the condtion becomes false.
Menu example
We can also put if inside while, and vice-versa. Here is a menu, in which the user is presented
with a series of choices. Typing stop takes out of the menu.
#while/if menu
reply = raw_input("Choose a, b, c, or stop: ")
while reply !="stop":
if reply =="a":
print "choice a"
elif reply=="b":
print "choice b"
elif reply == "c":
print "choice c"
else:
print "error in choice"
#end if
reply = raw_input("Choose a, b, c, or stop")
#end while
print "Done"
| |