That Blue Square Thing

AQA Computer Science GCSE

This page is up to date for the new AQA 8525 syllabus for exams from 2022.

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:

counter <- 0
WHILE counter < 4
OUTPUT counter
counter <- counter + 1
ENDWHILE
# outputs 0, 1, 2, 3

The Python syntax is similar:

counter = 0
while counter < 4:
print(counter)
counter = counter + 1
# outputs 0, 1, 2, 3

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:

value = 0 # need to have a failed value stored to enter the loop
while value <= 5:
value = int(input("Enter a value greater than 5: "))
# keeps looping until a value greater than 5 entered

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.