AQA Computer Science GCSE
Programming Concepts - Repetition
Indefinite Repetition - WHILE loops
Indefinite repetition repeats a block of code until a condition of some kind is met.
WHILE loops are the most common way of doing this - and the only way that works in Python.
They continue until the condition specified by the loop control variable is no longer met. So, the block of code loops "WHILE the condition is True" and stops looping when it becomes False.
The pseudocode syntax is:
WHILE counter < 4
counter <- counter + 1
# outputs 0, 1, 2, 3
The Python syntax is similar:
while counter < 4:
counter = counter + 1
As always with Python, watch the indents and make sure you don't forget the colon (the :) at the end of the loop line.
Using WHILE to help with data input
One of the really cool uses of a while loop is to manage data input - say when you expect a user to center a certain sort of value.
In this example, I want the user to enter a number that's greater than 5:
while value <= 5:
Note that less than or equal to (<=) is used in the while line - I want to do the loop until I get a value that is greater than 5.