>A Byte of Python

The while statement

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.

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.