For Loops

A free sample lesson from Python Fundamentals

The idea

Picture a character running a lap around a track - one full lap for every single item you're counting through. A for loop in Python does exactly that: for i in range(5) runs its indented block once for each number from 0 up to (but not including) 5 - five laps, five numbers: 0, 1, 2, 3, 4. Miscounting the starting or ending point is exactly why a loop might run one too many, or one too few, times.

What it actually is

A for loop repeats a block of code once for each item in a sequence - like counting through a fixed set of numbers, or going through every item in a list, one at a time.

How you write it

for variable in range(n):
    # runs n times, variable = 0, 1, ..., n-1
for variable in range(start, stop):
    # runs from start up to (not including) stop
for item in some_list:
    # runs once per item in the list

A worked example

for i in range(3):
    print("Lap", i)

range(3) produces the numbers 0, 1, 2 - three values in total, so the loop body runs exactly three times. Each time through, i takes the next value in that sequence, which is why the printed laps are 0, 1, 2, not 1, 2, 3.

for stars in range(2, 10, 2):
    print(stars)

range() accepts a third number: the step. range(2, 10, 2) starts at 2, stops before 10, and jumps by 2 each time, producing 2, 4, 6, 8 - like collecting stars two at a time instead of counting every single one.

Mistakes children actually make

Mistake 1: assuming range(5) starts at 1 - it actually starts at 0 and stops one before 5, so it produces 0, 1, 2, 3, 4 (five numbers, not six). Mistake 2: assuming range(1, 5) produces 5 numbers because of the 5 - the second number is where it STOPS (not included), so range(1, 5) only produces 1, 2, 3, 4 - four numbers, one fewer than a beginner usually expects. Mistake 3: looping directly over a list's ITEMS (for pet in pets:) and then still trying to index into the list with pet, like pets[pet] - pet is already the actual value ('cat'), not a position number, so this crashes or misbehaves; only loop with range(len(pets)) if the position itself is actually needed, not just the value.

Then they try it

In the app this lesson continues with the animated explanation, spoken aloud, and then the practice: Make your character do a repeating action exactly 5 times using a for loop over range(). The editor runs your child’s real code and checks the result, with their coding buddy reacting to what they wrote.

Try it free