Turtle Shapes
Draw a Square With a Loop
In the Turtle Move and Turn chapter, you drew a square by writing forward() and left() four times each.
A for loop can repeat the two lines for you:
Example
Draw a square with a for loop:
import turtle
t = turtle.Turtle()
for i in range(4):
t.forward(100)
t.left(90)
turtle.done()
Result:
The loop runs 4 times. Each time, the turtle draws one side and turns at the corner.
Draw a Triangle
A triangle has three sides, so the loop runs 3 times:
Example
Draw a triangle:
import turtle
t = turtle.Turtle()
for i in range(3):
t.forward(100)
t.left(120)
turtle.done()
Result:
Why does the turtle turn 120 degrees? To get back to where it started, the turtle must make one full turn in total, which is 360 degrees. With 3 corners, each turn is 360 / 3 = 120 degrees.
Any Shape With Equal Sides
The same rule works for any shape with equal sides. At each corner, the turtle turns 360 divided by the number of sides:
Example
Draw a shape with 5 sides:
import turtle
t = turtle.Turtle()
sides = 5
for i in range(sides):
t.forward(80)
t.left(360 / sides)
turtle.done()
Result:
Change sides to 8, and the turtle draws a shape with 8 sides.
Shapes With a Function
Put the loop inside a function, and you can draw a shape with one line of code:
Example
Draw three shapes with a function:
import turtle
t = turtle.Turtle()
def polygon(sides, size):
for i in range(sides):
t.forward(size)
t.left(360 / sides)
polygon(3, 80)
polygon(4, 80)
polygon(5, 80)
turtle.done()
Result:
All three shapes start at the same position, so they share the same bottom side.
Draw a Circle
Use circle() to draw a circle. The number is the radius, in pixels:
Example
Draw a circle with a radius of 50:
import turtle
t = turtle.Turtle()
t.circle(50)
turtle.done()
Result:
The turtle draws the circle by walking along its edge, turning left as it goes. That is why the circle is above the start position, and not around it.
Part of a Circle
Add a second number to draw only a part of the circle. The second number is how many degrees of the circle to draw:
Example
Draw half a circle:
import turtle
t = turtle.Turtle()
t.circle(50, 180)
turtle.done()
Result: