- Home
- Lessons
- KS3 Computing
- Python: loops
Python: loops
🎬 The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
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
A for loop repeats a set number of times. It is a count-controlled loop.
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.
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
A while loop repeats while a condition is True. It is a condition-controlled loop.
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.
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
total = 0
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.
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.
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.