How to Draw Triangle Using Turtle in Python - Simple Guide
To draw a triangle using
turtle in Python, create a turtle object and use a loop to move forward and turn 120 degrees three times. This draws three equal sides forming a triangle.Syntax
Here is the basic syntax to draw a triangle using the turtle module:
import turtle: Imports the turtle graphics module.t = turtle.Turtle(): Creates a turtle object to draw.t.forward(distance): Moves the turtle forward by the specified distance.t.right(angle): Turns the turtle clockwise by the specified angle.turtle.done(): Keeps the window open until closed by the user.
python
import turtle t = turtle.Turtle() t.forward(100) # Move forward by 100 units t.right(120) # Turn right by 120 degrees t.forward(100) t.right(120) t.forward(100) turtle.done()
Example
This example draws an equilateral triangle with sides of length 150 pixels. It shows how to use a loop to repeat the forward and turn commands three times.
python
import turtle def draw_triangle(side_length): t = turtle.Turtle() for _ in range(3): t.forward(side_length) t.right(120) turtle.done() draw_triangle(150)
Output
A window opens showing a triangle with three equal sides drawn by the turtle.
Common Pitfalls
Common mistakes when drawing a triangle with turtle include:
- Not turning exactly 120 degrees, which prevents the shape from closing properly.
- Forgetting to call
turtle.done(), causing the window to close immediately. - Using inconsistent side lengths or angles, resulting in a non-triangular shape.
python
import turtle t = turtle.Turtle() t.forward(100) t.right(90) # Wrong angle, should be 120 nt.forward(100) t.right(90) t.forward(100) turtle.done()
Output
The turtle draws an open shape that is not a triangle because the angles are incorrect.
Quick Reference
Remember these key points when drawing a triangle with turtle:
- Use
t.forward(distance)to draw sides. - Turn
t.right(120)degrees to form an equilateral triangle. - Repeat the forward and turn steps three times.
- Call
turtle.done()to keep the window open.
Key Takeaways
Use a loop to repeat moving forward and turning 120 degrees three times to draw a triangle.
Always turn exactly 120 degrees to close the triangle shape properly.
Call turtle.done() at the end to keep the drawing window open.
Use consistent side lengths for an equilateral triangle.
Import the turtle module and create a turtle object before drawing.