Lesson 3 of 35Python
Python · Lesson 3 · 20 minutes
Loops – repeating things
What you'll learn
- Run code several times with
forandrange() - Repeat with
whileas long as something is true - Recognise and avoid endless loops
Why loops?
Imagine you have to print “Hello” a hundred times. A hundred lines of print("Hello")? Far too much work. A loop repeats code for you.
The for loop
for goes through a sequence of values one after the other. range(5) produces the numbers 0, 1, 2, 3, 4 – five numbers, starting at 0.
for lap in range(5):
print(f"Lap {lap}")
print("Done!")Press Steps and watch the variable lap. You’ll see Python jumping back to the for line again and again.
range can do more:
| Call | Numbers |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 20, 5) | 0, 5, 10, 15 |
range(3, 0, -1) | 3, 2, 1 |
Calculating in a loop
Loops are great for adding things up. Here we add all numbers from 1 to 100:
total = 0
for number in range(1, 101):
total = total + number
print(f"The total is {total}.")The while loop
while repeats as long as a condition is true. That’s handy when you don’t know in advance how often.
money = 20
while money >= 7:
money = money - 7
print(f"Bought a cinema ticket, {money} euros left.")
print("Not enough money any more.")Watch out, endless loop: If the condition never changes,
whileruns forever. Trywhile True: print("Help")– and then press Stop.
Remember: Use
forwhen you know how often. Usewhilewhen you repeat until something happens.
Quick check
Before you start the task: what does this program print? Type your guess – then Python works it out.
total = 0
for number in range(1, 4):
total = total + number
print(total)Your task
Your turn
Program the countdown for a rocket launch: print the numbers from 10 down to 1, each on its own line, followed by Liftoff!. Use a loop – ten print() calls don't count.
# Countdown from 10 to 1, then "Liftoff!"- Something to think about
The first ten lines must be 10, 9, 8 … 1. Tip –
range(10, 0, -1)counts backwards. - Which command helps?
After the 1 there should be exactly one line “Liftoff!” – and nothing else.
Use
fororwhileinstead of printing every number separately. - Gap code – fill in the ___
for number in ___: print(___) print(___)
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
for number in range(10, 0, -1):
print(number)
print("Liftoff!")For fast learners
Pro task
Build a number pyramid with height rows. Row 1 shows 1, row 2 1 2, row 3 1 2 3 – and so on up to row height. The numbers are separated by exactly one space.
height = 4
# One row per pass of the loopShow pro solution
height = 4
for row in range(1, height + 1):
numbers = []
for number in range(1, row + 1):
numbers.append(str(number))
print(" ".join(numbers))