Learning goals
- Explain how a
forloop repeats instructions.- Use
range()to choose how many times instructions repeat.- Draw a shape with repeated Turtle commands.
for loop?A loop repeats instructions. First, look at the commands to draw a square without a loop:
import turtle as otto
otto.forward(50)
otto.left(90)
otto.forward(50)
otto.left(90)
otto.forward(50)
otto.left(90)
otto.forward(50)
otto.left(90)

When a turtle drawing uses the same commands many times, a loop can repeat them for you. This program uses a loop:
import turtle as otto
for side in range(4):
otto.forward(50)
otto.left(90)
Predict: how many times does the turtle turn?
otto.forward(50) and otto.left(90) four times. So the turtle draws the same square as before.
Both versions draw the same square. The loop is better here, because it is shorter and avoids repeating commands.
The loop repeats the commands that are indented. An indented line starts with a few spaces.
To indent a line, press Tab. Python adds 4 spaces.
The Tab key is on the left side of your keyboard. It often shows two arrows.

The loop ends when a line starts at the left edge again. That line is no longer part of the loop.
Don’t forget the colon
The line with
foralways ends with a colon (:). The colon tells Python that the indented commands belong to the loop. Many students forget it. Then Python stops with an error.
Try it yourself: Click the Run button. The drawing appears below the code.
Then change 4 to 3 and 90 to 120. Click Run again. Which shape do you get?
import turtle as otto
for side in range(4):
otto.forward(50)
otto.left(90)
This student forgot to indent otto.left(90). What will the turtle draw?
import turtle as otto
for side in range(4):
otto.forward(30)
otto.left(90)
otto.forward(30) is indented, so only that line repeats. The turtle moves forward 4 times without turning. After the loop, it turns left only once.
Does your loop draw something strange? Then check which lines are indented.
range(4) work?range(4) makes the loop repeat four times. Use another number to repeat more or less often.
The loop variable side holds the current number. A variable is a name for a value.
The instructions do not use this variable. You could choose another name, such as number.
range(4) give?
range(4) gives the numbers 0, 1, 2 and 3. That is four numbers, so the loop repeats four times. Python often starts counting at zero. An elevator also marks the ground floor with 0.The loop keeps the code shorter and easier to read. You only need to change the repeated instructions once, which helps avoid mistakes. Loops are especially useful when you need to repeat instructions many times.
| Idea | What it means |
|---|---|
for loop |
Repeats a group of instructions. |
range(4) |
Repeats the loop four times. |
| Indentation | Shows which instructions belong inside the loop. Press Tab to indent. |