- Home
- Lessons
- GCSE & IGCSE Computer Science
- Repetition and iteration: for and while
Repetition and iteration: for and while
🎬 The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
Loops save you from writing the same line again and again. Choosing the right loop is a key exam skill.
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.
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)
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
prices = [4, 10, 3, 8]
total = 0
for p in prices:
total = total + p
print(total)
Output: 25
What does this print?
n = 1
while n < 100:
n = n * 3
print(n)
- n: 1 → 3 → 9 → 27 → 81 → 243
- 243 < 100 is False, so the loop stops.
Answer: 243
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.
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.