Python: loops
Loops repeat code so you do not have to type it again and again. Python has two kinds: for loops and while loops.
for loops
for i in range(5):
print("Hi")
prints Hi 5 times.
range(5) gives 0, 1, 2, 3, 4. range(1, 5) gives 1, 2, 3, 4: it stops one before the end number.
range(2, 11, 2) counts up in 2s: 2, 4, 6, 8, 10.
while loops
count = 10
while count > 0:
count = count - 3
print(count)
count goes 10, 7, 4, 1, -2. When count is no longer more than 0, the loop stops and -2 is printed.
Use while when you do not know in advance how many repeats you need, for example asking until the user types the right password.
Running totals
for n in range(1, 5):
total = total + n
print(total)
Each time round, n is added to total: 0 + 1 + 2 + 3 + 4 = 10.
If the condition of a while loop never becomes False, you get an infinite loop.
What does this print?
total = 0
for n in range(1, 5):
total = total + n
print(total)
- range(1, 5) gives 1, 2, 3, 4.
- total: 1, 3, 6, 10.
Answer: 10
for loops repeat a fixed number of times (range stops one before the end number). while loops repeat while a condition is True. A condition that never becomes False makes an infinite loop.
- NOT
- A Boolean operator that flips its input: True becomes False and False becomes True.
- AND
- A Boolean operator that gives True (1) only when both inputs are True.
- Condition
- An expression that is either True or False, such as score > 50, used in if statements and while loops.
- Infinite loop
- A loop that never stops because its condition never becomes False.
- For loop
- A count-controlled loop that repeats a set number of times.
- While loop
- A condition-controlled loop that repeats while its condition is True.
Try two quick questions
See if it has sunk in. Answers are marked straight away.
2 more questions
Try each one, then tap to check.
How many times does this print Hello?
for i in range(4):
print("Hello")Show the answer
Answer: 4
range(4) gives 0, 1, 2, 3: 4 times.
What is the last number printed?
for n in range(2, 6):
print(n)Show the answer
Answer: 5
range(2, 6) gives 2, 3, 4, 5. It stops before 6.
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.
Facts checked against the sources below, 27 October 2026. Last updated 2 October 2026. Spotted a mistake? Tell us and we will fix it.