Menu

Condition Controlled Iteration (While Loops)

Loop Control and Termination

A while loop repeats its body as long as its condition is True, so you must set it up so that the condition can eventually become False — otherwise the loop never stops.

Giving the condition a chance to change

Any variable used in the condition must be given a value before the loop is reached, because the condition is tested before the very first pass. Without a value, the program stops with a runtime error; if the value given already makes the condition False, the body is skipped altogether.

At least one of those variables must then be changed inside the loop body. Changing it after the loop is no use, because the loop never gets that far. Here a reward card collects points until it reaches 100:

points = int(input("How many points do you have? "))
while points < 100:
    print("Not enough points for a reward yet.")
    earned = int(input("How many points did you earn today? "))
    points = points + earned  # update the variable used in the condition
print("Reward unlocked!")

Output when the user types 40, 70:

How many points do you have? 40
Not enough points for a reward yet.
How many points did you earn today? 70
Reward unlocked!

Each pass adds the day's points to points, so the total creeps towards 100 and the condition points < 100 finally becomes False. The condition is tested again at the start of every pass, using the new value.

Flowchart of the reward-points while loop: input points, test points < 100, output a message, input earned, points = points + earned and back to the test; No leads to Reward unlocked and End.

Infinite loops

If nothing inside the loop can make the condition False, you have an infinite loop. The condition is still True, so the body runs again and again: the program keeps repeating that block and never moves on to the statements after the loop. It looks frozen, or simply never finishes.

This is not a syntax error — every line is legal, so the program does run. It is a logic or runtime problem, and you fix it by adding or repairing the update inside the loop, or by correcting the condition so it tests the right thing.

Why choose a while loop

A while loop is more flexible than a for loop when you do not know in advance how many repetitions are needed — the points total might reach 100 after three turns or thirty. The price of that flexibility is that you, the programmer, are responsible for making sure the loop will terminate.

Practise this