Menu

Condition-Controlled Iteration

Condition-controlled iteration

Condition-controlled iteration repeats a section of code while a condition is true, stopping once it becomes false. The condition is checked while the program is running, so the number of repeats is decided at run time rather than when the program is written.

Use it when you cannot know the number of repeats

Some jobs have a fixed size: seven days in a week, twelve questions in a quiz. When you already know the count, a count-controlled loop is the right tool. Many jobs are not like that, though. How many attempts a player needs, how many customers buy today, or how many values you add before the user types a stopping value all depend on what happens while the program runs. Guessing a maximum and using a fixed count goes wrong both ways: guess too low and the program gives up too early, guess too high and it loops pointlessly once the real work is done. A condition-controlled loop stops as soon as its condition becomes false, so it repeats only as many times as it is needed.

Where you meet it

  • asking again until the correct password is typed
  • a guessing game where the player keeps guessing until they are right or run out of attempts
  • adding up values until a stopping value is entered
  • a menu that reappears until the user chooses to quit
  • selling items while stock remains

Worked example

A snack machine keeps selling while there is stock left. The number of items loaded is typed in when the program runs, so the number of passes is not known until then.

stock = int(input("Items in machine: "))  # how many are loaded today
while stock > 0:                          # carry on while there is something to sell
    stock = stock - 1                     # one more item sold
    print("Item sold. Left:", stock)
print("Machine empty")

Output when the user types 3:

Items in machine: 3
Item sold. Left: 2
Item sold. Left: 1
Item sold. Left: 0
Machine empty

The condition is written as the reason to carry on โ€” keep going while stock is above zero. Writing the stopping test on its own, such as stock == 0, would describe the same job backwards: the condition would be false at the start when stock is 3, so nothing would ever be sold.

Practise this