Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.6 (2 of 3): Repeating with loops

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
LoopA part of a program that repeats.for, while
IterationOne run through a loop. It also means repeating steps.the loop runs 5 times
Count-controlled loopA loop that runs a set number of times.for i in range(5)
Condition-controlled loopA loop that runs while a condition is True.while saved < 50
forThe Python word for a count-controlled loop.
whileThe Python word for a condition-controlled loop.
range()Makes the numbers a for loop counts through.range(5) gives 0 to 4
Infinite loopA loop that never stops, because its condition never becomes False.
VariableA name that holds a value.saved = 0
FunctionA named piece of code that does one job.print()
Trace tableA 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

Code: python
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 writeThe loop countsHow many times
range(5)0, 1, 2, 3, 45
range(1, 6)1, 2, 3, 4, 55
range(3)0, 1, 23

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

CodeNumbers it givesHow it works
range(0, 10, 2)0, 2, 4, 6, 8Start at 0. Go up by 2. Stop before 10
range(3, 0, -1)3, 2, 1Start 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Try it: loop over a list

Code: python
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

Code: python
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

Stepsavedweekssaved < 20 ?
Start00True
After iteration 151True
After iteration 2102True
After iteration 3153True
After iteration 4204False, 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

BenefitsDrawbacks
The code is short: write it once, run it many timesAn infinite loop can freeze the program
A change is made in one placeCounting from the wrong number is easy: range(5) starts at 0, not 1
Fewer typing mistakes than copying linesA loop inside a loop can be slow when there is a lot of data
Works for 5 items or 5 millionHard 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.

  1. times_table(n) gives back a list of the first 12 answers in the n times table. Use a for loop.
  2. add_up(numbers) gives back the total of the list. Use a for loop. Do not use sum().
  3. 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.

Code: python
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

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.