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.
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
Every for loop has the same four parts, and it is worth naming them out loud once.
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.
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.
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.
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.
| Pass | i holds | What prints |
|---|---|---|
| 1st | 0 | 0 |
| 2nd | 1 | 1 |
| 3rd | 2 | 2 |
| 4th | 3 | 3 |
| 5th | 4 | 4 |
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.
Break it on purpose
- Type the times table loop above and run it.
- Delete the colon at the end of the first line. Run it. Read the error.
- 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.
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.
Fractions
Math · 9 topics
What Is a Fraction?Equivalent FractionsSimplifying FractionsComparing FractionsAdding and Subtracting Fractions With the Same DenominatorAdding Fractions With Different DenominatorsFinding a Fraction of a NumberMixed Numbers and Improper FractionsFractions to DecimalsDecimals and percentages
Math · 7 topics
What Are Decimals?Comparing and Ordering DecimalsAdding and Subtracting DecimalsRounding DecimalsWhat Are Percentages?Finding a Percentage of a NumberFractions, Decimals and PercentagesScience: matter and the water cycle
Science · 5 topics
What Is Matter?Solids, Liquids and GasesChanging StateThe Water CycleMixtures and SolutionsWhole numbers
Math · 10 topics
Place Value to 1,000,000Rounding Whole NumbersAdding and Subtracting With RegroupingTimes Tables That Actually StickMultiplying by 10, 100 and 1000Long Multiplication, Step by StepShort DivisionLong Division, Step by StepFactors, Multiples and PrimesOrder of OperationsForces and energy
Science · 6 topics
Forces and MotionFrictionGravity, Mass and WeightLevers and Simple MachinesEnergy and Its FormsSimple CircuitsStuck 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.