Thirty friends, one message
You want to send "Happy birthday" to 30 friends. Would you type it 30 times?
No. You would find a way to repeat the job. A program can repeat steps too. It can do it 30 times, or a million times, without getting tired.
Key words
| Word | What it means | Example |
|---|---|---|
| Loop | A part of a program that repeats. | for, while |
| Iteration | One run through a loop. It also means repeating steps. | the loop runs 5 times |
| Count-controlled loop | A loop that runs a set number of times. | for i in range(5) |
| Condition-controlled loop | A loop that runs while a condition is True. | while saved < 50 |
| for | The Python word for a count-controlled loop. | |
| while | The Python word for a condition-controlled loop. | |
| range() | Makes the numbers a for loop counts through. | range(5) gives 0 to 4 |
| Infinite loop | A loop that never stops, because its condition never becomes False. | |
| Variable | A name that holds a value. | saved = 0 |
| Function | A named piece of code that does one job. | print() |
| Trace table | A table where you write the value of each variable after each step. |
The cells students fill in are left blank in this preview.
Count-controlled: the for loop
You know how many times to repeat. Use a for loop.
This is a count-controlled loop. Each run through the loop is one iteration. The function range(5) gives the numbers 0, 1, 2, 3 and 4. That is five iterations. In for i in range(5), the name i holds the current number.
Try it: a for loop
for i in range(5):
print("Happy birthday, friend number", i)
# Change 5 to 8 and run it again.
# Notice that the counting starts at 0.
Make a free account to save your work and track your progress.
What range() gives you
| You write | The loop counts | How many times |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | 5 |
| range(1, 6) | 1, 2, 3, 4, 5 | 5 |
| range(3) | 0, 1, 2 | 3 |
The cells students fill in are left blank in this preview.
range() with two numbers
Note
You can give range() two numbers: where to start and where to stop. The loop counts up by 1 and stops before the stop number.
Extra: range() with three numbers
| Code | Numbers it gives | How it works |
|---|---|---|
| range(0, 10, 2) | 0, 2, 4, 6, 8 | Start at 0. Go up by 2. Stop before 10 |
| range(3, 0, -1) | 3, 2, 1 | Start at 3. Go down by 1. Stop before 0 |
The cells students fill in are left blank in this preview.
Quick check: for loops
Have a go
Quick check: for loops
3 questionsTry it: loop over a list
names = ["Sam", "Aisha", "Tom"]
for name in names:
print("Happy birthday,", name)
# A loop can also build a list. Start with an empty list. Then use append to add to the end.
# i * i means i times i.
squares = []
for i in range(1, 6):
squares.append(i * i)
print(squares)
Make a free account to save your work and track your progress.
Condition-controlled: the while loop
Sometimes you do not know how many times. You save 5 pounds each week. You stop when you reach 50.
Use a while loop. It is a condition-controlled loop. It checks the condition before every iteration. It stops when the condition is False.
Try it: saving money
saved = 0
weeks = 0
while saved < 50:
saved = saved + 5
weeks = weeks + 1
print("Week", weeks, "saved", saved)
print("Done after", weeks, "weeks")
# Change 50 to 72 and run it again.
Make a free account to save your work and track your progress.
The while loop as a flowchart
flowchart TD
start(["Start"]) --> setup["saved = 0, weeks = 0"]
setup --> check{"Is saved less than 50?"}
check -->|"True"| body["saved = saved + 5, weeks = weeks + 1"]
body --> check
check -->|"False"| show[/"Output weeks"/]
show --> stop(["End"])
A loop must change its own condition
Warning
Many people think a while loop always stops by itself. It stops only when its condition becomes False. If nothing in the loop changes the condition, it never stops. Forget the line that adds to saved, and the program stops responding. Always ask: what makes this condition become False?
Trace table: saving to reach 20
| Step | saved | weeks | saved < 20 ? |
|---|---|---|---|
| Start | 0 | 0 | True |
| After iteration 1 | 5 | 1 | True |
| After iteration 2 | 10 | 2 | True |
| After iteration 3 | 15 | 3 | True |
| After iteration 4 | 20 | 4 | False, the loop stops |
The cells students fill in are left blank in this preview.
Which loop would you use?
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Watch: each iteration
Press Play on the short film below. It runs loops like the ones above, one iteration at a time, and adds a row for each iteration under the code. Watch where range() stops, and what makes a while loop stop.
Film: repeating with loops
Repeating with loops
Every scene, as text
- for i in range(5): repeats the indented line. range(5) gives the numbers 0, 1, 2, 3 and 4, and each run through the loop is one iteration. In iteration 1, i is 0, so print(i) prints 0; then i is 1, 2, 3 and 4. Five iterations print five lines on the screen.
- Myth (false): range(5) ends at 5. It stops before 5, the stop number, so the last i is 4. It still runs five iterations, because it starts at 0.
- To count from 1 to 5, give range() two numbers: where to start and where to stop. range(1, 6) starts at 1 and stops before 6, so i is 1, 2, 3, 4 and 5.
- Myth (false): a while loop stops by itself. Here the line saved = saved + 5 is missing. The loop checks saved < 20 before every iteration; saved stays 0, so the answer is always True and the loop never stops. The film shows four iterations, the fourth faded; Python would go on for ever, and the last line is never reached.
- The cure: ask what makes the condition become False. saved = saved + 5 changes saved in every iteration: 5, 10, 15, then 20. Now saved < 20 is False, so the loop stops and the last line prints Done after 4 weeks.
Benefits and drawbacks of loops
| Benefits | Drawbacks |
|---|---|
| The code is short: write it once, run it many times | An infinite loop can freeze the program |
| A change is made in one place | Counting from the wrong number is easy: range(5) starts at 0, not 1 |
| Fewer typing mistakes than copying lines | A loop inside a loop can be slow when there is a lot of data |
| Works for 5 items or 5 million | Hard to read when there are many loops inside loops |
The cells students fill in are left blank in this preview.
Your turn: three loops
Write three functions with loops.
times_table(n)gives back a list of the first 12 answers in the n times table. Use a for loop.add_up(numbers)gives back the total of the list. Use a for loop. Do not usesum().weeks_to_save(goal, per_week)gives back how many weeks it takes to reach the goal. Use a while loop.
Press Run Tests to check.
def times_table(n):
# Give back a list of the first 12 answers in the n times table.
# For n = 2 the list starts [2, 4, 6] and ends with 24.
# Use a for loop.
return []
def add_up(numbers):
# Give back the total of the numbers in the list.
# Use a for loop. Do not use the sum() function.
return None
def weeks_to_save(goal, per_week):
# You start with 0 pounds. You save per_week pounds each week.
# Give back how many weeks it takes to reach the goal.
# Use a while loop.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Your turn: draw a loop
Draw a flowchart for this job. Ask the user for a password. If it is not "bus42", say "Wrong" and ask again. When it is right, say "Welcome". Use a decision diamond, and an arrow that goes back up to make the loop. Your teacher will check it.
flowchart TD
start(["Start"]) --> ask[/"Input the password"/]
ask --> check{"Add the decision here"}
check --> stop(["End"])
Make a free account to save your work, or press Start lab to work through the whole lesson.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Exit quiz
Have a go