0
0
PythonHow-ToBeginner · 3 min read

How to Use Turtle in Python: Simple Drawing with Turtle Module

To use turtle in Python, first import the module with import turtle. Then create a turtle object and use its methods like forward() and right() to draw shapes on the screen.
📐

Syntax

The basic syntax to use the turtle module involves importing it, creating a turtle object, and calling its methods to move and draw.

  • import turtle: Loads the turtle module.
  • t = turtle.Turtle(): Creates a turtle named t.
  • t.forward(distance): Moves the turtle forward by distance pixels.
  • t.right(angle): Turns the turtle clockwise by angle degrees.
  • turtle.done(): Keeps the window open until closed by the user.
python
import turtle

t = turtle.Turtle()
t.forward(100)  # Move forward 100 pixels
t.right(90)     # Turn right 90 degrees
t.forward(50)   # Move forward 50 pixels
turtle.done()   # Finish and keep window open
💻

Example

This example draws a square by moving the turtle forward and turning right 90 degrees four times.

python
import turtle

screen = turtle.Screen()
t = turtle.Turtle()

for _ in range(4):
    t.forward(100)  # Move forward 100 pixels
    t.right(90)     # Turn right 90 degrees

screen.mainloop()  # Keep the window open
Output
A window opens showing a square drawn by the turtle.
⚠️

Common Pitfalls

Common mistakes when using turtle include forgetting to call turtle.done() or screen.mainloop(), which causes the window to close immediately. Another mistake is not creating a turtle object before calling movement methods.

Also, mixing up angles or distances can lead to unexpected drawings.

python
import turtle

# Wrong: calling forward without creating a turtle object
# turtle.forward(100)  # This will cause an error

# Right way:
t = turtle.Turtle()
t.forward(100)
turtle.done()
📊

Quick Reference

CommandDescription
import turtleImport the turtle module
t = turtle.Turtle()Create a turtle object
t.forward(distance)Move turtle forward by distance pixels
t.backward(distance)Move turtle backward by distance pixels
t.right(angle)Turn turtle clockwise by angle degrees
t.left(angle)Turn turtle counterclockwise by angle degrees
t.penup()Lift the pen to move without drawing
t.pendown()Put the pen down to draw while moving
turtle.done()Keep the window open until closed

Key Takeaways

Import the turtle module and create a turtle object to start drawing.
Use movement methods like forward() and right() to control the turtle.
Always call turtle.done() or screen.mainloop() to keep the window open.
Create the turtle object before calling its methods to avoid errors.
Use penup() and pendown() to control when the turtle draws.