Sentinel-controlled processing
Process input or stream data until a read operation produces a false value.
Python · Const
The while statement repeatedly executes an indented suite while its condition is true. An optional else suite runs when the condition becomes false, but not when break exits the loop.
A while loop repeatedly evaluates its condition and executes its indented body whenever that condition is true. When the condition becomes false, the loop stops; an optional else suite then runs unless the body exited through break, while continue skips the remaining body and starts the next condition check.
while assignment_expression:
suite
[else:
suite]| Name | Type | Description |
|---|---|---|
assignment_expression | expression | Expression evaluated before each iteration; its truth value determines whether the suite runs. |
suite | suite | Indented statements executed when the expression is true. |
else suite | suite | Optional indented statements executed after normal termination. |
count = 3
while count > 0:
print(count)
count -= 1
else:
print("done")Counts down while the condition remains true, then runs the else suite because the loop ends without break.
Process input or stream data until a read operation produces a false value.
Retry work while an attempt counter or readiness condition remains true.
Poll for a changing state until it reaches a desired condition.
The condition is tested before every iteration, including the first. If it is false initially, the body is skipped and the optional else suite runs.
Follow-up: What prevents the else suite from running? A break statement in the loop body terminates the loop without executing that suite.
The loop repeatedly evaluates its condition. A true result executes the body, while a false result ends the loop and can trigger else.
Follow-up: What does continue do? It skips the remainder of the current body and returns to condition testing.
The syntax is while followed by an assignment expression, a colon, and an indented suite; an else clause is optional. The condition can be any expression whose truth value controls repetition.
Follow-up: Can the body execute zero times? Yes; a false condition on the initial test skips the body entirely.
if statementfor statementbreak statementcontinue statementassignment expressions