Draw with Python (Turtle Power)
Learn how to use turtle to draw shapes and patterns.
We'll cover the following...
Let’s do something fun and creative—use Python to draw pictures.
We’ll use a built-in Python module called turtle to control a pen on the screen.
Introducing the turtle
Try this:
import turtle pen = turtle.Turtle() pen.forward(100)
Line 3:
pen = turtle.Turtle()brings a turtle onto the screen that you can control. We are giving it a name:pen. You can call it anything you like. From now on, whenever we saypen, Python knows we’re talking about that turtle.Line 4:
pen.forward(100)tells the turtle (referred to aspen) to move forward by 100 steps (pixels). The turtle draws a line as it moves, like dragging a pen on paper.
A turtle appears on the screen and draws a line that is 100 pixels long!
Add more movements
We can move the turtle around with different commands:
import turtle pen = turtle.Turtle() pen.forward(100) pen.right(90) pen.forward(100) pen.right(90)
Keep going—you’re drawing a square one side at a time.
Use loops to draw shapes
Loops make it easier to draw repeated patterns:
import turtle
pen = turtle.Turtle()
for _ in range(4):
pen.forward(100)
pen.right(90)
turtle.done()This is the beginning of turtle-powered geometry.
Color and style
We can make our drawing more visually interesting:
import turtle
pen = turtle.Turtle()
pen.color("blue")
pen.pensize(3)
pen.speed(2)
pen.forward(150)Change the pen color, thickness, and speed!