GCSE Computer Science
Python for loops โ GCSE Computer Science
What is a for loop?
A for loop runs a block of code a set number of times. Not "until something happens" โ that's a while loop. A for loop is for when you already know how many times you need to repeat something. Print a times table. Count through a list. Repeat an action exactly ten times. That's what a for loop is for.
The basic structure
for i in range(5):
print(i)
This runs five times. i takes a new value on each iteration โ 0, then 1, then 2, then 3, then 4. The indented line is the loop body. Everything indented runs each time. Everything that isn't indented doesn't.
The indentation isn't decoration. It's how Python knows what's inside the loop.
Using range()
range() is how Python counts. Three versions appear in GCSE exams and you need to know all three:
range(5)โ 0, 1, 2, 3, 4. Five values. Starts at zero.range(1, 6)โ 1, 2, 3, 4, 5. Starts at 1, stops before 6.range(0, 10, 2)โ 0, 2, 4, 6, 8. The third number is the step.
The thing students most often get wrong: range(5) gives you five numbers, but they go from 0 to 4 โ not 1 to 5. That distinction appears on mark schemes more than you'd expect.
A worked example
for i in range(1, 11):
print(i * 3)
The 3 times table from 3 to 30. The loop runs ten times โ once for each value from 1 to 10. On the first iteration i is 1, so it prints 3. On the last, i is 10, so it prints 30.
Try changing the range. What happens if you use range(1, 11, 2)? Run it and see.
What examiners actually test
Three things come up repeatedly in GCSE for loop questions: tracing a loop and stating the output, writing a loop that produces a specific result, and working out how many times a loop runs. The last one trips people up most often โ count the values range() produces, not the start and end numbers.
The best way to build the intuition is to write a loop, predict the output, then run it. If you were wrong, work out why before you move on.
Want structured Python lessons? Python Coach covers for loops and 26 other lessons with 195 challenges โ free 60 teaching day trial.
Start learning →