Session 3 of 5 · 60 minutes
Loops
Make the computer repeat work for you with for loops, while loops and range().
Goals
By the end of this session you can:
- Repeat code a fixed number of times with a for loop and range()
- Repeat code until something changes with a while loop
- Keep a running total (an accumulator) inside a loop
- Stop a loop early with break
Words to know
- loop
- Code that repeats.
- iteration
- One trip through the loop.
- range()
- A function that produces a sequence of numbers to loop over.
- accumulator
- A variable that collects a result, like a running total.
- infinite loop
- A loop that never stops because its condition never becomes False.
The lesson
Step 1: The for loop
Imagine printing “Hello” five times by writing print("Hello") five times. A loop does it for you.
for i in range(5):
print("Hello", i)Hello 0
Hello 1
Hello 2
Hello 3
Hello 4range(5) makes the numbers 0, 1, 2, 3, 4. The loop variable i takes each one in turn. Notice:
- Counting starts at 0, not 1.
range(5)stops before 5.- The lines inside the loop are indented, just like an
if.
Step 2: Start, stop and step
range() can take up to three numbers: where to start, where to stop (not included) and how big each step is.
for n in range(1, 6):
print(n)1
2
3
4
5for n in range(10, 0, -2):
print(n)10
8
6
4
2Step 3: Keeping a running total
A very common pattern: create a variable before the loop, then update it inside the loop.
total = 0
for n in range(1, 5):
total = total + n
print("Added", n, "total is", total)
print("Final total:", total)Added 1 total is 1
Added 2 total is 3
Added 3 total is 6
Added 4 total is 10
Final total: 10Common mistake: If you write
total = 0inside the loop, it resets to zero on every trip. Set it once, before the loop.
total += n is a shorter way to write total = total + n.
Step 4: The while loop
A for loop runs a set number of times. A while loop runs as long as its condition is true. It is perfect when you don’t know in advance how many times you need.
count = 3
while count > 0:
print(count)
count = count - 1
print("Go!")3
2
1
Go!The loop changes count each time. If it didn’t, the condition would stay true forever and the program would never stop: an infinite loop. If that happens, press the Stop button in your editor.
Step 5: Stopping early with break
break ends a loop immediately. It is often used with while True, a loop that runs until you tell it to stop.
while True:
word = input("Type a word (or 'quit'): ")
if word == "quit":
break
print("You typed", word)
print("Bye!")Type a word (or 'quit'): apple
You typed apple
Type a word (or 'quit'): quit
Bye!Exercise
Countdown
- Use a
forloop withrange()to print the numbers from 10 down to 1. - After the loop, print
Liftoff! - Change your program so the user chooses the starting number with
input().
Need a hint?
range(10, 0, -1) counts down from 10 to 1. The third number is the step.
Small project
Times table and total
Build a program that prints a times table and adds up the answers.
- Ask the user for a number.
- Print its times table from 1 to 10, one line each, like
7 x 3 = 21. - Add up all ten answers in a variable called
totaland printTotal: ...at the end. - Use a
whileloop to ask again until the user types0.
Stretch it: Print the times table only for the even multipliers (2, 4, 6, 8, 10).
Quiz
Check your understanding
Pick one answer for each question. Your score appears right in the page; nothing is sent anywhere.
Feedback on this lesson
Teachers and students: tell us what worked and what didn't. We read this to improve the curriculum.
Received
Thank you for the feedback.
The Education team reviews lesson feedback to improve the curriculum.
Preview mode: this form is not connected to a destination yet, so nothing was sent. Set its web address in src/data/config.json.