July 4, 2010 4 Comments
The structure of a while statement is:
while <condition>: <do stuff>
The program answers the question: is the condition true or false? If it is true, it does stuff in the <do stuff> section. When it is finished it goes back up to the top and repeats the process again and again until the condition is false:
>>> a = 10 >>> while a > 0: ... a = a-1 ... print a ... 9 8 7 6 5 4 3 2 1 0
The ordering here is a little odd because I forgot to print a in the first line. What is printed is the value of a after 1 has been subtracted from it. Note now that the value stored in a has been changed while the program did that stuff. It is now 0 (zero, not that letter in the alphabet after n).
>>> a 0
Anything that can be put in the <condition> part of an if statement can also go in while‘s <condition> statement.
>>> while True: ... b = raw_input('Type stuff here: ') ... if b == 'quit': ... break ... print 'You typed -> '+b ... Type stuff here: hi You typed -> hi Type stuff here: what's this do? You typed -> what's this do? Type stuff here: hello? Is someone there? You typed -> hello? Is someone there? Type stuff here: quit >>>
In this example, we’ve used a weird condition- True. The computer, when asked the question, “Is True true or is it false?” will have to answer “True is true!”. It will do this every time the condition is encountered. Therefore this is a loop which would go on for ever. Or, it would go on forever if we hadn’t used another instruction break. What break does, is it ‘breaks’ out of the loop created by while and continues its execution at the next line following the <do stuff> block. You should be able to see this because it didn’t print out “You typed -> quit” when I typed quit. That code was skipped. Break will also work to break out of a loop for the for command.
>>> for a in range(20): ... print a ... if a == 10: ... break ... 0 1 2 3 4 5 6 7 8 9 10
Do you see it broke out of the loop when a was 10?
You can give set up an initial condition before starting the while loop and update it within the loop:
>>> a = 5 >>> while a < 100: ... print a ... a = a+10 ... 5 15 25 35 45 55 65 75 85 95
But you need to be careful that the loop doesn’t go on forever! If the program is not responsive try Ctrl-C to stop it:
>>> while True: ... pass ... ^CTraceback (most recent call last): File "<stdin>", line 1, in <module> KeyboardInterrupt