Writing and Refining Algorithms
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.
The condition follows the word while and is tested each time, usually a comparison such as temperature < 200. Every pass follows the same order:
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.
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).
OCR GCSE Computer Science · Trace Tables
OCR GCSE Computer Science · Writing and Refining Algorithms
OCR GCSE Computer Science · Condition-Controlled Iteration