Your First Python Loop

A loop is the first idea in programming that is genuinely new. Everything before it is a list of instructions read top to bottom, which is how a recipe works. A loop sends the computer backwards, and once a child sees why that is worth doing, most of the rest of programming is variations on it.

Coding: first steps in Python · topic 1 of 1Grades 5 to 8Programming9 min read7 practice questions

Why loops exist

A loop tells the computer to go back and do something again, instead of you writing it out again.

That is the whole idea, and it sounds too small to matter until you need it a thousand times. Writing a line out five times is only mildly annoying; writing it out five thousand times is impossible, and a program that draws a grid or checks every name on a list is doing exactly that sort of thing.

Here is the same job done both ways. Start with the version with no loop in it.

print("hello")
print("hello")
print("hello")
print("hello")
print("hello")
Five lines, five hellos. Now make it a hundred.
for i in range(5):
    print("hello")
Two lines, five hellos. Change the 5 to 100 and it is still two lines.

Both programs print the same thing. The second one is not shorter for the sake of being clever. It is shorter because the number of repeats has been pulled out into one place, and a program where one idea lives in one place is a program you can change without breaking.

The shape of a for loop

for i in range(5):the line that sets the loop upprint("hello")this line is the loop's bodydone it 5 times?nogo againyescarry on with the rest of the program
Follow the blue arrow. The computer runs the body, checks whether it has done it enough times, and if it has not, it goes back up. That arrow going backwards is the only thing a loop does that ordinary instructions cannot.

Every for loop has the same four parts, and it is worth naming them out loud once.

1
The word for

It announces that a loop is starting. Python has other kinds of loop, but this is the one to learn first, because it repeats a known number of times and therefore always stops.

2
A name for the counter

Usually i, though count or row is often clearer. It is a variable that holds a different number on every pass, and you did not have to create it: the loop makes it for you.

3
The colon at the end of the line

It says the next indented lines belong to the loop. Leave it off and Python stops with a syntax error, which is the most common first error there is.

4
The indented body

Every line pushed in by four spaces is inside the loop and repeats. The first line that is not indented is outside it and runs once, after the loop has finished.

The rule worth keeping

In Python the indent is not tidiness, it is meaning. Moving a line four spaces to the left takes it out of the loop, and the program will then do something different without a single word being changed.

for i in range(3):
    print("inside")
print("outside")

# inside
# inside
# inside
# outside
Three insides and one outside. The last print is not indented, so it waits until the loop has finished and then runs once.

Why range starts at 0

range(5) gives five numbers, and they are 0, 1, 2, 3, 4. Not 1 to 5. This catches everyone once, and it is worth understanding rather than memorising, because the same rule turns up everywhere else in programming.

Passi holdsWhat prints
1st00
2nd11
3rd22
4th33
5th44

Read the middle column and the count in the left column together. There are five passes, which is what range(5) promised, and the largest number reached is one less than five. Think of range(5) as saying five of them, starting at nothing rather than up to five, and it stops being surprising.

If you genuinely want 1 to 5, say so: range(1, 6) starts at 1 and stops before 6.

Using the loop variable

So far i has just been sitting there. It becomes useful the moment the body uses it, because then every pass does something slightly different.

for i in range(1, 13):
    print(i, "x 7 =", i * 7)
The seven times table, in two lines. Change the 7 and you have any table you like.

That is the point at which most children stop seeing loops as a way to save typing and start seeing them as a way to describe a pattern. The loop is not repeating the same thing twelve times. It is doing the same kind of thing twelve times, with one number moving underneath it.

Try it at home

Break it on purpose

  1. Type the times table loop above and run it.
  2. Delete the colon at the end of the first line. Run it. Read the error.
  3. Put the colon back and remove the indent instead. Run it. Read that error too.

Breaking a working program on purpose is the fastest way to learn what each piece was holding up, and it is much less frightening than meeting the same error for the first time in the middle of something you care about. Python's errors name the line number, which is worth pointing out while it is on screen.

Common mistakes

1. Forgetting the colon

Python answers with SyntaxError: expected ':' and points at the line. It is the single most common first error, and the good news is that it is also the easiest to read: Python is telling you exactly what is missing and exactly where.

2. Getting the indent wrong

Forget it entirely and Python says IndentationError, which is fine because it stops. The dangerous version is indenting some lines and not others, because then the program runs perfectly and quietly does the wrong thing. A loop that was meant to print a total on every pass prints it once at the end, and nothing anywhere says so.

3. Expecting range to include the last number

A child writes range(1, 10) to count to ten and gets nine numbers. Nothing errors, the program just quietly does slightly less than was intended, and off by one mistakes like this one survive for years in real software written by adults. Say the range out loud as start here, stop before there.

Practice questions

Check yourself

No sign up. Nothing is sent anywhere, the score stays on this device.

0 / 7

What to learn next

The natural next step is if, because a loop that can make a decision on each pass is where programs start to feel alive. After that, lists, so that the loop has something real to go through rather than just counting.

For parents

You do not need to know any Python to help here. Ask your child to read the loop out loud as an instruction to a person: do this, then go back and do it again, five times. If they can say it in plain words they understand it, and if they cannot, that is the exact sentence to work on rather than the code.

Keep going

Still stuck on this?

Send us the question and a teacher will answer it. No charge, and you do not have to be a student here.

What to learn next

Everything in the Learning Hub

Every topic is free and every one ends with practice questions. Start anywhere.

Stuck on this topic? Get one class, free.

A tutor works through it live with your child, one on one, and sends you a short written report afterwards. No card needed.

See our Math programme