Control Flow
While Loops
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
liftoffA 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: okNotes
- Use
whilewhen changing state decides whether the loop continues. - Update loop state inside the body so the condition can become false.
- Prefer
forwhen you already have a collection, range, iterator, or generator to consume.
See also
- related: For Loops
- prerequisite: Sentinel Iteration
- related: Break and Continue
Run the complete example
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.