The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause.
Example 6.3. Using the while statement
#!/usr/bin/python # Filename : while.py number = 23 stop = False while not stop: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' stop = True # This causes the while loop to stop elif guess < number: print 'No, it is a little higher than that.' else: # you must have guess > number to reach here print 'No, it is a little lower than that.' else: print 'The while loop is over.' print 'I can do whatever I want here.' print 'Done.'
$ python while.py Enter an integer : 50 No, it is a little lower than that. Enter an integer : 22 No, it is a little higher than that. Enter an integer : 23 Congratulations, you guessed it. The while loop is over. I can do whatever I want here. Done.
Here, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly - there is no need to repeatedly execute the program for repeated guesses. This aptly demonstrates the use of the while statement.
We move the raw_input and if statements to inside the while loop and set the variable stop to True before the while loop. First, we check the variable stop and if it is True, we proceed to execute the corresponding while-block. After this block is executed, the condition is again checked which in this case is the stop variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block if it exists, and then continue to the next statement in the block containing the while statement.
The else block is executed when the while loop condition becomes False - this may even be the first time that the condition is checked. If there is an else clause for a while loop, it is always executed unless you have a while loop which loops forever without ever breaking out!
The True and False are just special variables which are assigned the value 1 and 0 respectively. Please use True and False instead of 1 and 0 wherever it makes more sense, such as in the above example.
The else-block is actually redundant since you can put those statements in the same block (as the while statement) after the while statement. This has the same effect as an else-block.
Remember that you can have an else clause for the while loop.