Control Flow

While Loops

while repeats until changing state makes a condition false.

Use while when the condition, not an iterable, controls repetition. Here the loop owns the countdown state and updates it each time through the body.

Source

remaining = 3
while remaining > 0:
    print(f"launch in {remaining}")
    remaining -= 1
print("liftoff")

Output

launch in 3
launch in 2
launch in 1
liftoff
foriterable exhaustedwhilecondition falsesentinelmarker returned
while repeats the body until the condition becomes false; the back-edge returns to the test each pass.

A sentinel loop stops when a special value appears. The loop does not know in advance how many retries it will need; it keeps going until the state says to stop.

Source

responses = iter(["retry", "retry", "ok"])
status = next(responses)
while status != "ok":
    print(f"status: {status}")
    status = next(responses)
print(f"status: {status}")

Output

status: retry
status: retry
status: ok

Notes

See also

Run the complete example

Example code

Expected output

launch in 3
launch in 2
launch in 1
liftoff
status: retry
status: retry
status: ok

Execution time appears here after you run the example.