Menu

Writing and Refining Algorithms

While Loops

A while loop repeats a block of code and is condition-controlled: it tests a condition before every pass and runs the block only while that condition is true. Because the test comes first, a while loop can run zero times. If the condition is false when it is first checked, the indented block is skipped completely and the program continues with the first line after the loop.

Testing the condition on every pass

The condition follows the word while and is tested each time, usually a comparison such as temperature < 200. Every pass follows the same order:

  1. The condition is tested at the start of the pass.
  2. If it is true, the indented block runs once.
  3. The program returns to the while line and tests the condition again.
  4. When the test is false, the loop ends and the lines after it run.

Flowchart of a while loop: the condition people_waiting > 0 is tested first. If yes, a customer is served, people_waiting goes down by 1 and the flow returns to the test; if no, "Queue empty" is output and the program stops. With nobody waiting the body is skipped, so a while loop can run 0 times.

temperature = 20
while temperature < 200:
    print("Heating:", temperature)
    temperature = temperature + 50
print("Oven ready at", temperature)

Output:

Heating: 20
Heating: 70
Heating: 120
Heating: 170
Oven ready at 220

Starting at 20, the test 20 < 200 is true, so the loop runs and the oven heats to 70 before going back to the top. The test succeeds again at 70, 120 and 170, and the loop ends once the temperature reaches 220. Had the temperature started at 200, the test would have been false straight away and the block would never have run.

Making the loop end

For a while loop to finish, something inside the block must change a value used in the condition. Here, temperature = temperature + 50 moves the temperature towards 200, so the condition eventually becomes false. If no line changed it, the condition would stay true and the loop would never end. A loop that can never finish is called an infinite loop (also called an endless loop).

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms