Drawing shapes with turtle loops
A for loop draws a turtle shape by repeating one side: the same forward()
and left() run again for every side, so a square takes three lines, not eight.
Read For Loops and Turtle graphics in Python first.
Draw a square with a loop
import turtle
t = turtle.Turtle()
for side in range(4):
t.forward(100)
t.left(90)
The two indented lines run four times, once for each side.
Draw any regular polygon
On its way round a regular shape, the turtle turns one full circle: 360
degrees. So each corner turns 360 / sides.
import turtle
t = turtle.Turtle()
sides = 6
turn = 360 / sides
for side in range(sides):
t.forward(80)
t.left(turn)
print(turn)
Change sides to 5 or 8 and run it again. The same loop draws every
regular polygon.
Draw a star
Turn more than halfway round at each point and the lines cross. A turn of
144 gives a five-pointed star:
import turtle
t = turtle.Turtle()
for point in range(5):
t.forward(150)
t.right(144)
Five turns of 144 make 720 degrees: the turtle goes round twice.
Grow a spiral with the loop counter
Use the loop variable in a move, and each side changes:
import turtle
t = turtle.Turtle()
for i in range(40):
t.forward(i * 4)
t.left(121)
The sides get 4 steps longer each time. A turn of 121 instead of 120
makes the triangles twist.
Repeat a whole shape
Put one loop inside another to repeat a whole shape. The inner loop draws a square; the outer loop turns a little and draws it again:
import turtle
t = turtle.Turtle()
for petal in range(12):
for side in range(4):
t.forward(80)
t.left(90)
t.left(30)
See also: The range() Function, Nested Loops & Ifs, Turtle circles.
Your turn
Put the four moves inside a for loop that runs 4 times, so the turtle
climbs four steps.
import turtle
t = turtle.Turtle()
# add one line, then indent the four lines below it
t.forward(20)
t.left(90)
t.forward(20)
t.right(90)
print(t.position())
Expected output
(80.00,80.00)