The while statement is used to create loops. Like other conditional statements, while will execute its indented code block when the condition following while is True, and continuously loop re-executing the code block until the statement is False.
It is necessary to change the value of whatever the condition is contingent upon in order for the loop to exit. It is common to see while True: used to create a main loop in a program that loops forever because True is always True.
It is also common to see while variable comparison CONSTANT: as a means to iterate through a series of values. In this case the variable will be changed or reevaluated in the code block following the while statement and the loop will exit when the comparison yields False.
An else statement can follow a while loop to provide code that executes once after the loop is terminated by a False condition. This optional else statement can be useful for 'clean-up' tasks following a series of operations performed in a while loop.
while condition:
code block
while condition:
code block
else:
code block # executes when while loop completes
condition : any True/False conditional statement resulting from comparison of one or more values and any logical operators
code block : any block of code indented any amount of space or tab stops. It is typical to see an incrementing statement or some other means of changing the comparison variable included in the code block so the loop will eventually exit.
Executes code in the indented code block while the condition is True and exists when the condition evaluates False.
code.py output:
countdown from 5...
a is 5...
a is 4...
a is 3...
a is 2...
a is 1...
a is 0...
countdown complete
count up from 0
b is 0
b is 1
b is 2
b is 3
b is 4
b is 5
b is 6
b is 7
b is 8
while loop finished, resetting b
b is 0
reapeating counts