Drawing with Code: Turtle Graphics
Give a friendly turtle a pen and watch your loops turn into pictures
turtle. It gives you a little on-screen turtle that holds a pen. When the turtle moves, it draws a line. By telling it to move, turn, and change color, you can draw shapes, spirals, and grids -- and your loops and functions suddenly become pictures you can see.
- make a turtle and move it with
forwardandbackward, - turn it with
rightandleft(measured in degrees), - change the pen color and size, and lift the pen with
penup, - use a
forloop to draw shapes like squares and triangles, - write a function that names a reusable drawing.
1. What is turtle graphics?
Imagine a tiny turtle sitting in the middle of a sheet of paper. The turtle is holding a pen that touches the paper. Whenever the turtle crawls forward, the pen leaves a line behind it. If you turn the turtle first and then let it crawl, the line goes in a new direction. That is the whole idea of turtle graphics: you draw by giving the turtle simple movement commands.
You already know how to use loops and functions from earlier topics. Turtle graphics is a fun way to see them work. A loop can draw the four sides of a square without you writing the same line four times. A function can wrap up a whole drawing under one name so you can reuse it.
The turtle lives in a module named turtle, which comes with Python. You do not need to install anything extra.
2. Setting up your turtle
First you bring in the tool with import turtle. Then you make a turtle to command and store it in a variable so you can talk to it. At the very end you call turtle.done() so the drawing window stays open for you to look at.
import turtle
pen = turtle.Turtle()
pen.forward(100)
turtle.done()
Here pen is the name we gave our turtle. You can pick any name -- some people use t -- but a clear name helps. From now on we send every command to pen, like pen.forward(100). The dot means "ask pen to do this".