The while
loop has the following syntax:
while <<boolean expression>>:
<<statement>>
<<statement>>
<<statement>>
.
.
.
The statements under the while
clause get executed repeatedly as long as the boolean expression evaluates to True
.
For example, the following program prints “y” to the standard output until someone kill it, just like the yes
utility in Unix.
while True: print "y"
Infinite loops are rarely useful. Hence, most while
loop’s condition involves variables whose values change every time the loop is run.
Here’s an example of a variable used in a while loop whose value changes because of the user’s input.
x = 0 sum = 0 while x >= 0: x = float(raw_input("Enter a number (a negative number to stop): ")) sum += x print "The sum of all non-negative numbers entered is", str(sum) + "."
Here’s an example of a counter variable, which is a variable holding an integer value which is increased by one in each iteration.
i = 0 while i < 10: print i i += 1
The counter variable lets us know which iteration we are in. So, based on its value, we can do something different in each loop.