The idea of “turtle programming” dates back to the 1960’s and originated with Seymour Papert. He developed a robot turtle with a physical pen in it. Children would steer the robot around and create drawings with the pen by writing programs in a language called Logo.
Today, we can play with virtual turtles in a fully graphical and non-robotic way. To do so, we will make use of another feature of Python - code libraries. A library is a collection of existing code designed to help programs perform some task. Using a library means we do not have to figure out how to handle all the details of a particular problem - the library code will take care of many of those details for us. In the case of making a virtual turtle, our program will need to have a way to keep track of where the turtle is, a way to move the turtle around, etc… The turtle library will handle these details for us.
To use a library, we need to tell Python we want to use the library with an import statement. In the program below, we start with import turtle to tell Python we want to make use of the turtle library. To use commands from the library, we use dot notation: we type the name of the library, then a dot ., then the command. The line alex = turtle.Turtle() calls the Turtle() command from the turtle library to make a new turtle - we name that turtle alex.
The turtles that we make are objects that have behaviors we can access with dot-notation. We use these to tell the turtle alex to move around on the screen using commands like alex.forward(150). As the turtle moves around it draws a line behind itself.
Try clicking the Save & Run button below to see what the following program does.
Checkpoint13.4.2.
Which direction will alex move when the code below executes?
import turtle
alex = turtle.Turtle()
alex.forward(100)
Up
Check which way alex moved first in the example above
Right
Check which way alex moved first in the example above
Down
Check which way alex moved first in the example above
Left
Turtles start off facing right by default
Just by going forward, backward, left, and right, we can have a turtle draw a shape:
Checkpoint13.4.3.
What shape will the program below draw when you click on the Run button?
import turtle # use the turtle library
zari = turtle.Turtle() # create a turtle named zari
zari.setheading(90) # Point due north
zari.forward(100) # tell zari to move forward by 100 units
zari.right(90) # turn by 90 degrees
zari.forward(100) # tell zari to move forward by 100 units
zari.right(90) # turn by 90 degrees
zari.forward(100) # tell zari to move forward by 100 units
zari.right(90) # turn by 90 degrees
zari.forward(100) # tell zari to move forward by 100 units
zari.right(90) # turn by 90 degrees