While Statements

The while statement allows you to repeat one or more actions while a condition remains True. Such a statement often is called a loop. Consider the following “pseudocode” scenario about grocery shopping to understand the logic behind a while statement:

While there are more items on my shopping list,
Buy next item and cross it off my list

If the condition “there are more items on my shopping list” is true, you perform the action “Buy next item and cross it off my list.” You repeat this action while the condition remains true. You stop repeating this action when the condition becomes false—that is, when you’ve crossed all items off your shopping list.

Let’s use a while statement to find the first power of 3 larger than 50:

product = 3
while product <= 30:
	product = product * 30

First, we create product and initialize it to 3. Then the while statement executes as follows:

  1. Python tests the condition product <= 50, which is True because product is 3. The statement in the body of the while loop multiplies product by 3 and assigns the result (9) to product. One iteration of the loop is now complete.

  2. Python again tests the condition, which is True because product is now 9. The body’s statement sets product to 27, completing the second iteration of the loop.

  3. Python again tests the condition, which is True because product is now 27. The body’s statement sets product to 81, completing the third iteration of the loop.

  4. Python again tests the condition, which is finally False because product is now 81. The loop now terminates.

The program evaluates product to see its value, 81, which is the first power of 3 larger than 50. If this while statement were part of a larger program, execution would continue with the next statement in sequence after the while loop.

Something in the while statement’s body must change product’s value, so the condition eventually becomes False. Otherwise, a logic error called an infinite loop occurs. Such an error prevents the while statement from ever terminating—the program appears to “hang.” Beware of accidentally generating an infinite loop in your programs!