Repetition and iteration: for and while

Loops save you from writing the same line again and again. Choosing the right loop is a key exam skill.

Practise this lesson free (6 questions)

More tools

Count-controlled: for

Use for when you know how many times to repeat.
range(5) gives 0, 1, 2, 3, 4. range(1, 6) gives 1 to 5. range(0, 10, 2) counts in 2s: 0, 2, 4, 6, 8.
The end value is never included.

Condition-controlled: while

Use while when you repeat until something happens, such as a correct password.
The condition is checked before each pass. If it is never False, the loop runs for ever: an infinite loop.
n = 1
while n < 100:
    n = n * 3
print(n)

Iteration over a data structure

for can visit every item in a list or string in turn.
prices = [4, 10, 3, 8]
total = 0
for p in prices:
    total = total + p
print(total)
Output: 25
Worked example

What does this print?
n = 1
while n < 100:
    n = n * 3
print(n)

  1. n: 1 → 3 → 9 → 27 → 81 → 243
  2. 243 < 100 is False, so the loop stops.

Answer: 243

Key idea

for repeats a known number of times (range stops before the end value) or visits every item. while repeats while a condition is True and may run zero or many times.

Key words
Iteration
Repeating code, or visiting each item of a data structure in turn.
String
A sequence of characters.

All GCSE and International GCSE Computer Science key terms and definitions →

Quick check

Try two quick questions

See if it has sunk in. Answers are marked straight away.

Extra practice

2 more questions

Try each one, then tap to check.

  1. How many times does this print Hi?
    for i in range(5):
    print("Hi")

    Show the answer

    Answer: 5

    range(5) gives 0, 1, 2, 3, 4: that is 5 times.

  2. What numbers does this print? Write them separated by spaces.
    for i in range(1, 12, 4):
    print(i)

    Show the answer

    Answer: 1 5 9

    Start at 1, add 4 each time and stop before 12: 1 5 9.

Check you have got it

Answer 6 quick questions with instant marking. If you get one wrong, GCSE-ready shows you why and gives you another go. It is free, and you do not need an account.

Video for this lesson coming soon. Subscribe on YouTube

Sources and references

Facts checked against the sources below, 17 October 2026. Last updated 2 October 2026. Spotted a mistake? Tell us and we will fix it.

What do exam command words like explain and evaluate mean? →

Related lessons