Section 9.2 The while Statement
A basic building block of all programs is to be able to repeat some code over and over again. We refer to this repetitive idea as iteration. In this section, we will explore some mechanisms for basic iteration.
In addition to conditional execution, Python also supports repetitionβrunning the same code multiple timesβusing the
while statement. The
while statement provides a general mechanism for iterating. When used with other code it can be used to repeat code in a
while loop. Similar to the
if statement, it uses a boolean expression to control the flow of execution. The body of while (code indented one space in from the while statement) will be repeated as long as the controlling boolean expression evaluates to
True.
The following two figures show the flow of control. The first focuses on the flow inside the while loop and the second shows the while loop in context.
Letβs look at our first Python statement that can be used to build an iteration.
Here is a simple example that counts down from 10 to 0.
count is a normal variable here, but since it is governing the
while loop it is also called the
loop variable.
Line 2 here is the
loop condition. It must always be a boolean expression that will evaluate to
False or
True.
Lines 3 and 4 are the
loop body. The loop body is always indented. The indentation determines exactly what statements are "in the loop". The loop body is run each time the loop is repeated.
On each
iteration or
pass of the loop, a check is done to see if the loop condition is True (if
count is greater than zero). If it is not (this is called the
terminating condition of the loop), the loop has finished. Program execution continues at the next statement after the loop body.
If
count is greater than zero, the loop body is executed again.
At the end of each execution of the body of the loop, Python returns to the
while statement, to see if the loop should repeat.
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. An endless source of amusement for computer scientists is the observation that the directions written on the back of the shampoo bottle (lather, rinse, repeat) create an infinite loop.
Here is a a program that sums the integers from 1 to N using a while statement. To do 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 as
aNumber is less than or equal to the bound, we should keep going.
You can almost read the
while statement as if it were in natural language. It means, while
aNumber is less than or equal to
aBound, continue executing the body of the loop. Within the body, each time, update
theSum using the accumulator pattern and increment
aNumber. After the body of the loop, we go back up to the condition of the
while and reevaluate it. When
aNumber becomes greater than
aBound, the condition fails and flow of control continues to the
return statement.
The same program in codelens will allow you to observe the flow of execution.
More formally, here is the flow of execution for a
while statement:
-
Evaluate the condition, yielding
False or
True.
-
If the condition is
False, exit the
while 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. An endless source of amusement for computer scientists is the observation that the directions written on the back of the shampoo bottle (lather, rinse, repeat) create 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. When using a
while loop you have to control the loop variable yourself. You give it an initial value, test for completion, and then make sure you change something in the body so that the loop terminates. That also makes a while loop harder to read and understand than the equivalent for loop. So, while you
can implement definite iteration with a while loop, itβs not a good idea to do that. Use a for loop whenever it will be known at the beginning of the iteration process how many times the block of code needs to be executed.
Checkpoint 9.2.4.
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)
n starts at 10 and is incremented by 1 each time through the loop, so it will always be positive
The loop will run as long as n is positive. In this case, we can see that n will never become non-positive.
answer starts at 1 and is incremented by n each time, so it will always be positive
While it is true that answer will always be positive, answer is not considered in the loop condition.
You cannot compare n to 0 in while loop. You must compare it to another variable.
It is perfectly valid to compare n to 0. Though indirectly, this is what causes the infinite loop.
In the while loop body, we must set n to False, and this code does not do that.
The loop condition must become False for the loop to terminate, but n by itself is not the condition in this case.
Checkpoint 9.2.5.
Write a while loop that is initialized at 0 and stops at 15. If the counter is an even number, add double its value to
total_score. If the counter is an odd number, subtract half its value from
total_score.
Checkpoint 9.2.6.
Write a function called
stop_at_one that takes an integer as a parameter, and performes the following operations on it until the integer equals 1: If the number is odd, multiply by 3 and add 1. If the number is even, divide by two. The function should then return how many iterations it took to reach 1.
You have attempted
of
activities on this page.