The while
StatementΒΆ
- There is another Python statement that can also be used to build an iteration.
- It is called the
while
statement. - Similar to the
if
statement, it uses a boolean expression to control the flow of execution. - The body of while will be repeated as long as the controlling boolean expression evaluates to
True
.
The following figure shows the flow of control.
- We can use the
while
loop to create any type of iteration we wish, including anything that we have previously done with afor
loop. - For example, the program in the previous section could be rewritten using
while
. - Instead of relying on the
range
function to produce the numbers for our summation, we will need to produce them ourselves. - To to this, we will create a variable called
aNumber
and initialize it to 1, the first number in the summation. - Every iteration will add
aNumber
to the running total until all the values have been used. - In order to control the iteration, we must create a boolean expression that evaluates to
True
as long as we want to keep adding values to our running total. In this case, as long asaNumber
is less than or equal to the bound, we should keep going.
Here is a new version of the summation program that uses a while statement.
The same program in codelens will allow you to observe the flow of execution.
Note
The names of the variables have been chosen to help readability.
More formally, here is the flow of execution for a while
statement:
- Evaluate the condition, yielding
False
orTrue
. - If the condition is
False
, exit thewhile
statement and continue execution at the next statement. - If the condition is
True
, execute each of the statements in the body and then go back to step 1.
- The body consists of all of the statements below the header with the same indentation.
- This type of flow is called a loop because the third step loops back around to the top.
- Notice that if the condition is
False
the first time through the loop, the statements inside the loop are never executed. - The body of the loop should change the value of one or more variables so that eventually the condition becomes
False
and the loop terminates. - Otherwise the loop will repeat forever. This is called an infinite loop.
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)