Compute with Turtles¶
A turtle here is not an animal. We are working with a virtual turtle, an idea that dates back to the 1960’s. The original robot turtle had a physical pen in it. The student-programmers would steer the robot around using programs, and create drawings with the pen.
Today, we can play with virtual turtles in a fully-graphical and non-robotic way. Below is a Python program that first reads in a library that contains the code to let us work with turtles (from turtle import *
). Then it creates a Screen, a space on the page for the turtle to move in and draw on (space = Screen()
). Next it creates a turtle named alex
(alex = Turtle()
), then has alex
move around on the screen (alex.forward(150)
) and when it moves it will draw. The part of any line that starts with a #
character is called a comment. Python and the computer ignores everything from the #
character to the end of the line. Comments explain what we’re doing in the programs and are intended to be read by people, not computers.
Try clicking the button below to see what the following program does.
Note
Notice that we tell alex
what to do in the code above using dot notation: alex.forward(150)
, alex.left(90)
, and alex.forward(75)
. That is how you communicate with a turtle. You use the name of the turtle followed by a .
and then what you want it to do.
- North
- Check which way alex moved first
- West
- Check which way alex moved first
- South
- Check which way alex moved first
- East
- Turtles start off facing east by default
csp-1-5-2: Which direction will alex move when the code below executes?
from turtle import *
space = Screen()
alex = Turtle()
alex.forward(100)
Just by going forward, backward, left, and right, we can have a turtle draw a shape.