While Loop (Python)

This tutorial module explains the syntax and usage of while loops.

While loops are loops that continue to run while a given condition is satisfied. This stands in contrast to for loops, which run over a range or sequence. (Compare the use of conditional logic here with if statements.)

i = 0

while i < 10:
 print(i)
 i = i + 1
> 0
> 1
> 2
> ...

This block of code prints the number stored for i with each loop, as long as i is less than 10. It is common to structure while loops using a value that is incremented with each loop. Note that in this example, the value is printed before it is incremented, meaning that the first value printed will be the value of i before the loop began.

Compare the results above with the following:

i = 0

while i < 10:
 i = i + 1 
 print(i)
> 1
> 2
> 3
> ....

Here the print statement follows the incrementing operation, so the output range is different.

We can use the addition assignment operator += as a more efficient way of incrementing i. The symbol += sums the values on either side and assigns the new value to the variable on the left:

i = 0

while i < 10:
 print(i)
 i += 1

The statement i += 1 is identical in function to i = i + 1.

Just as with if statements, while loops can be nested with other loops and control structures, and multiple conditions can be combined using the and keyword:

i = 0

while i < 10 and i != 8:
 print(i)
 i += 1

In this example, the loop ends at 7 because the value 8 fails to meet the conditions. Even though the value 9 theoretically meets both conditions, the loop does not restart.

For more, including how to use break, continue, and else statements with while loops, see the w3schools entry.