Next / Previous / Contents / TCC Help System / NM Tech homepage

6.5. The while statement

Use this statement when you want to perform a block B as long as a condition C is true:

while C:
    B
    ...

Here is how a while statement is executed.

  1. Evaluate C. If the result is true, go to step 2. If it is false, the loop is done, and control passes to the statement after the end of B.

  2. Execute block B.

  3. Go back to step 1.

Here is an example of a simple while loop.

>>> i = 1
>>> while i < 100:
...     print i,
...     i = i * 2
... 
1 2 4 8 16 32 64

This construct has the potential to turn into an infinite loop, that is, one that never terminates. Be sure that the body of the loop does something that will eventually make the loop terminate.