The while StatementΒΆ

The following figure shows the flow of control.

../_images/while_flow.png

Here is a new version of the summation program that uses a while statement.




(ch07_while1)

The same program in codelens will allow you to observe the flow of execution.

(ch07_while2)

Note

The names of the variables have been chosen to help readability.

More formally, here is the flow of execution for a while statement:

  1. Evaluate the condition, yielding False or True.
  2. If the condition is False, exit the while statement and continue execution at the next statement.
  3. If the condition is True, execute each of the statements in the body and then go back to step 1.

In the case shown above, we can prove that the loop terminates because we know that the value of aBound is finite, and we can see that the value of aNumber increments each time through the loop, so eventually it will have to exceed aBound. In other cases, it is not so easy to tell.

What you will notice here is that the while loop is more work for you — the programmer — than the equivalent for loop.

iter-3-1: The following code contains an infinite loop. Which is the best explanation for why the loop does not terminate?

n = 10
answer = 1
while n > 0:
    answer = answer + n
    n = n + 1
print(answer)





Next Section - The 3n + 1 Sequence