Skip to main content

Section 5.2 The while statement

One form of iteration in Python is the while statement. Here is the program for our table of squares and cubes using a while statement that produces the same output. Step through this program with codelens so you can see the repetition in action.
You can almost read the while statement as if it were English. It means, “While n is less than or equal to five, display the value of n , n squared, and n cubed; then increase the value of n by 1. When you get to 6 (which is not <= 5), exit the while statement and display the line of dashes.”
More formally, here is the flow of execution for a while statement:
  1. Evaluate the condition, yielding True or False.
  2. If the condition is false, exit the while statement and continue execution at the next statement.
  3. If the condition is true, execute the body and then go back to step 1.
This type of flow is called a loop because the third step loops back around to the top. We call each time we execute the body of the loop an iteration. For the above loop, we would say, “It had five iterations”, which means that the body of the loop was executed five times.
Figure 5.2.1 shows a flowchart for a generic while loop.
Figure 5.2.1. Flowchart of while Loop

Checkpoint 5.2.2.

We call each time we execute the body of the loop an ________.
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. The iteration variable is our name for the variable that changes each time the loop executes and controls when the loop finishes. If there is no iteration variable—if no variables change in the loop body—the loop will repeat forever, resulting in an infinite loop.

Checkpoint 5.2.3.

    Consider the code block below. What are the values of x and y when this while loop finishes executing?
    x = 2
    y = 5
    
    while (y > 2 and x < y):
        x = x + 1
        y = y - 1
    
  • x is 2; y is 5
  • Incorrect! These were the values of x and y at first, but they changed by the time the loop finished executing. Try again.
  • x is 5; y is 2
  • Incorrect! The while loop will finish executing before x and y reach these values. Try again.
  • x is 4; y is 3
  • Correct! The loop will terminate when x equals 4 and y equals 3 because at that point, x is not less than y.
  • x is 4; y is 2
  • Incorrect! The way the loop modifies x and y, it is impossible for y to be 2 when x is 4. Try again.
If you had difficulty with the preceding question, here’s the program as activecode. We have added a print statement so you can see the values of x and y at each iteration. You might also want to use codelens to see the values of x and y step by step.