28 Aug Admin
while <expr>: <statement(s)>
<statement(s)> represents the block to be repeatedly executed, often referred to as the body of the loop. This is denoted with indentation, just as in an
The controlling expression,
<expr>, typically involves one or more variables that are initialized prior to starting the loop and then modified somewhere in the loop body.
while loop is encountered,
<expr> is first evaluated in Boolean context. If it is true, the loop body is executed. Then
<expr> is checked again, and if still true, the body is executed again. This continues until
<expr> becomes false, at which point program execution proceeds to the first statement beyond the loop body.
n = 5 while n > 0: n -= 1 print(n)
4 3 2 1 0
Here’s what’s happening in this example:
5. The expression in the
whilestatement header on line 2 is
n > 0, which is true, so the loop body executes. Inside the loop body on line 3,
nis decremented by
4, and then printed.
- When the body of the loop has finished, program execution returns to the top of the loop at line 2, and the expression is evaluated again. It is still true, so the body executes again, and
- This continues until
0. At that point, when the expression is tested, it is false, and the loop terminates. Execution would resume at the first statement following the loop body, but there isn’t one in this case.