GCSE Computer Science
Python while loops โ GCSE Computer Science
What is a while loop?
A while loop keeps running as long as a condition is true. Not a fixed number of times โ that's a for loop. A while loop is for when you don't know in advance how many repetitions you'll need. Keep asking for input until the user enters something valid. Keep running a game until the player loses. Repeat until a condition is met.
The difference matters on mark schemes. Examiners use while loops specifically because the number of iterations isn't fixed โ that's the point of them.
The basic structure
count = 0
while count < 5:
print(count)
count = count + 1
The condition is checked before each iteration. If it's true, the loop body runs. If it's false, the loop ends. count starts at 0 and increases by 1 each time โ after five iterations, count is 5, the condition is false, and the loop stops.
The update inside the loop body is not optional. Without it, the condition never becomes false and the loop runs forever.
Input validation with while loops
password = input("Enter password: ")
while password != "secret":
print("Wrong password. Try again.")
password = input("Enter password: ")
print("Access granted.")
This is the classic while loop pattern in GCSE exams. The loop keeps running until the user enters the correct password. The number of attempts isn't fixed โ it depends on what the user types. A for loop couldn't do this. A while loop can.
Forgetting to update the loop variable inside the body. The condition never becomes false. The program appears to freeze. This is the most common cause of infinite loops in student exam answers.
What examiners actually test
Two patterns appear repeatedly: a count-controlled while loop where you need to trace the value of the counter, and an input-validation loop where you need to identify when the loop terminates. The most common mistake is forgetting that the condition is evaluated before the loop body runs โ if the condition is false at the start, the loop never runs at all.
The infinite-loop moment makes a great lesson โ once. What actually fixes it is repeated practice with feedback, which is the gap Python Coach was built to close: 195 challenges spread across 27 lessons, with progress tracking so you can see exactly who's still forgetting to update their loop variable. Sixty teaching days free, no card required.
Start your school's free trial →