16 A shortcut for repeating code
In Lesson 2, drawing a square meant typing t.forward(100) and t.right(90) four times in a row.
Python has a shortcut for repeating code: a for loop.
for i in range(4):
t.forward(100)
t.right(90)
for i in range(4): repeats the two lines underneath it — 4 times.
17 Square with a loop — you fill it in
Fill in the two blanks to make a square, then click Run.
Hint:
A square has 4 sides.
A right-angle turn is 90°.
Still stuck? Tap here
Fill in: range(4) and right(90)
18 Triangle with a loop — you fill it in
Same idea, different shape. Fill in the blanks.
A triangle has 3 sides.
360° ÷ 3 = ?
Still stuck? Tap here
Fill in: range(3) and right(120)
19 Rectangle with a loop — you fill it in
A rectangle has 2 different side lengths, so the repeated block is bigger — but it repeats fewer times. Fill in the blanks.
A rectangle has 4 sides, but this loop’s block already has 2 sides in it (one long, one short).
How many times must the block repeat to make all 4 sides?
Still stuck? Tap here
Fill in: range(2) and forward(80)
Challenge20 Now you try: a pentagon
A pentagon has 5 equal sides. This time, there’s no code to copy — you need to work out the turn angle yourself before you write the loop.
A full turn all the way around is 360°.
A pentagon has 5 corners.
What calculation would tell you the turn angle at each corner?
Still stuck? Tap here
A pentagon has 5 sides. 360° ÷ 5 = 72°.
for i in range(5):
t.forward(100)
t.right(72)
What you learned in this lesson
for i in range(n):repeats the indented lines underneath it n times- loops let us draw a shape’s sides with far less code than typing each one out
- a shape with equal sides repeats a short block many times (like the square and triangle)
- a shape with unequal sides repeats a bigger block fewer times (like the rectangle)
- for a shape with n equal sides, turn 360° ÷ n at each corner
Your certificate is locked
Go back and try the code boxes.
Change the code, click Run, and do this in at least 2 code boxes to unlock your certificate.
Well done! Type your name, check your certificate, then press Print.
Well done!
This certificate is awarded to
for completing Turtle Coding
Lesson 4: Shapes with Loops
You have:
- used a
forloop to repeat code - drawn squares, triangles and rectangles with loops
- worked out the turn angle for a pentagon