Le’ts learn how to draw a triangle in Python. We can easily do that using the turtle module.
These are the methods that we will use to create a triangle.
- Turtle(): It will instantiate a new turtle object.
- forward(): It takes a number and moves the turtle (pen) by that distance.
- left(): It turns the turtle to a given angle in the anti-clockwise direction. By default, it takes an angle in degrees.
- right(): It turns the pen in the clockwise direction.
- fillcolor(): This method sets the color of the shape to be drawn.
- begin_fill(): We need to call this method before drawing the shape that needs to be filled.
- end_fill(): We need to call this method after drawing the shape. It fills it with the given color.
Now that we know all the required functions, let’s get started and draw a basic triangle.
To draw a triangle in Python, use this code:
import turtle turt = turtle.Turtle() #instantiate a new object turt.fillcolor("cyan") #set the color of the triangle to cyan turt.begin_fill() turt.left(120) turt.forward(150) turt.left(120) turt.forward(150) turt.left(120) turt.forward(150) turt.end_fill() turtle.done()#pauses the program
Initially, we create a new turtle object. Then, we set the shape’s color to cyan and call the begin_fill() method. After that, we start drawing the triangle.
First, we rotate the pen 120o anti-clockwise, then move it forward 150 pixels in that direction. This is what we get.
Then, we need to go down. For that, we again rotate 120o anti-clockwise and then 150 pixels forward.
The last step is to draw a horizontal line to complete the triangle. We need to repeat the same step. The final triangle is given below.
Instead of repeating the same lines of code, we can use a loop. Let’s see.
import turtle turt = turtle.Turtle() #instantiate a new object turt.fillcolor("cyan") #set the color of the triangle to cyan turt.begin_fill() for i in range(0, 3): turt.left(120) turt.forward(150) turt.end_fill() turtle.done()
The above triangle is equilateral. Let’s now draw a right-angled triangle.
To draw a right-angled triangle, use this code:
import turtle turt = turtle.Turtle() #instantiate a new object turt.fillcolor("cyan") #set the color of the triangle to cyan turt.begin_fill() turt.left(90) turt.forward(150) turt.left(225) turt.forward(212.13) turt.left(225) turt.forward(150) turt.end_fill() turtle.done()
Output
Hey guys! It’s me, Marcel, aka Maschi. On MaschiTuts, it’s all about tutorials! No matter the topic of the article, the goal always remains the same: Providing you guys with the most in-depth and helpful tutorials!