How to Draw a Square Using Turtle in Python
Use the
turtle module in Python to draw a square by moving the turtle forward and turning it 90 degrees four times. The basic commands are forward() to move and right(90) to turn right by 90 degrees.Syntax
The basic syntax to draw a square with turtle involves these steps:
import turtle: Loads the turtle 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 right by the specified angle in degrees.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(90) # Turn right by 90 degrees turtle.done()
Example
This example draws a complete square by repeating the forward and right turn commands four times.
python
import turtle t = turtle.Turtle() for _ in range(4): t.forward(100) # Move forward by 100 units t.right(90) # Turn right by 90 degrees turtle.done()
Output
A window opens showing a square drawn by the turtle cursor.
Common Pitfalls
Common mistakes when drawing a square with turtle include:
- Forgetting to call
turtle.done(), which closes the window immediately. - Using incorrect turn angles (not 90 degrees) which results in shapes other than a square.
- Not repeating the forward and turn commands exactly four times.
python
import turtle t = turtle.Turtle() # Wrong: turning 60 degrees instead of 90 for _ in range(4): t.forward(100) t.right(60) # Incorrect angle turtle.done()
Output
The turtle draws a shape with 60-degree turns, not a square.
Quick Reference
Remember these key commands for drawing shapes with turtle:
| Command | Description |
|---|---|
t.forward(distance) | Move turtle forward by distance |
t.right(angle) | Turn turtle right by angle degrees |
t.left(angle) | Turn turtle left by angle degrees |
turtle.done() | Keep window open until closed |
Key Takeaways
Use
t.forward() and t.right(90) four times to draw a square.Always call
turtle.done() to keep the drawing window open.Turning by exactly 90 degrees is essential for a perfect square.
Repeat the move and turn commands four times for four sides.
Import the turtle module and create a turtle object before drawing.