|

# How To Draw Triangles In Python Turtle Drawing with Turtle in Python is really fun. In the past handful of tutorials, we learned how to import the Turtle module for use in our programs saw how to make the turtle (pen) move on the canvas, made the turtle change directions on the canvas, saw how to use loops in turtle, and made drawings of shapes using variables. Now we will take a look at drawing another type of Polygon, the triangle using the Turtle library in Python.

## Define A Triangle Function

To draw a triangle, we want to use a function, and it should make use of variables. We do this so that we can call the function many times if we like to draw many triangles of different sizes.

``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('triangle')

def draw_triangle(length=150):
for i in range(3):
forward(length)
left(120)

draw_triangle()

done()`````` Nice! The triangle function works. Notice that the loop uses 3 iterations shown by range(3) whereas when we drew a square it used 4 iterations in the loop. Another thing we notice is that we are passing in 120 as the degrees to turn for the left() function. Why is that? This is because when drawing a triangle, you need to use the outside angle rather than the inside angle. What we are drawing here is an equilateral triangle since all three angles of an equilateral triangle add up to 180 degrees. ## Drawing More Triangles

Now we can use the draw_triangle() function a couple of times in combination with moving the turtle to a different spot on the canvas for a nice effect.

``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('triangle')

def draw_triangle(length=150):
for i in range(3):
forward(length)
left(120)

draw_triangle()
right(180)
forward(100)
right(180)
draw_triangle(200)

done()`````` The following iteration takes that idea a step further to draw three triangles in different spots on the canvas.

``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('triangle')

def draw_triangle(length=150):
for i in range(3):
forward(length)
left(120)

draw_triangle()
right(180)
forward(100)
right(180)
draw_triangle(200)
right(180)
forward(100)
right(180)
draw_triangle(250)

done()`````` ## Drawing Triangles In A Loop

Calling the draw_triangle() inside of a loop makes for some really cool effects.

``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('triangle')

def draw_triangle(length=150):
for i in range(3):
forward(length)
left(120)

for i in range(20):
draw_triangle()
right(1)

done()`````` ``````from turtle import *

drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('triangle')

def draw_triangle(length=150):
for i in range(3):
forward(length)
left(120)

for i in range(40):
draw_triangle()
right(10)

done()`````` |