while Loops

A while loop repeats as long as a condition is true.

Output:

3
2
1
done

Python checks the condition before each repetition.

Anatomy of a while Loop

A useful while loop has three parts:

  1. a value before the loop
  2. a condition
  3. an update inside the loop

In the countdown example:

Without the update, the condition may stay true forever.

When to Use while

Use while when you do not know the exact number of repetitions in advance, but you do know the condition for continuing.

Examples:

  • repeat until an error is small enough
  • keep reading until there is no more input
  • keep trying while a counter remains positive

For beginner code, prefer for when the number of repetitions is clear. Use while when the stopping condition is the main idea.

Countdown

The loop stops when remaining is no longer greater than zero.

Runs locally with Python in your browser.

Ready to run.

Make the Loop Condition Change

This loop never changes remaining:

The condition stays true. That is an infinite loop.

Exercise: Find the stopping value

After this loop finishes, what is the value of remaining?

Compute it first, then check your number.

HintTrace each update

Start at 2. Subtract one after each successful condition check.

SolutionThe loop stops at zero

The updates change remaining from 2 to 1, then from 1 to 0. At zero, remaining > 0 is false, so the final value is 0.

Every While Loop Needs Progress

A while loop is controlled by its condition. Always ask: what changes inside the loop so the condition can eventually become false?