Skip to content

12 min read

American Corners
Educator-ready reference unit

Turtle graphics and variables

Python, and a robot called Turtle

Python is a programming language. That just means it is a way to give a computer clear, step-by-step instructions. People reach for Python in many fields, including artificial intelligence, robotics, data processing and machine learning, partly because it reads more like plain English than most other languages.

The friendliest way to start is with Turtle. Think of Turtle as a small robot living on the screen. It can move and it can draw a line as it goes, and you steer it with Python. The robot lives in a flat, two-dimensional world: it starts in the middle of the screen and it starts facing to the right. Every instruction you give is relative to where it is and which way it is pointing right now.

For the rest of this lesson, picture that robot. Everything you write is really just you telling it where to go.

Start with something that works

Before any theory, here is a complete program. Four useful lines, and it draws one blue line 80 pixels long.

import turtle

pen = turtle.Turtle()
pen.color("blue")
pen.forward(80)
turtle.done()

That is the whole shape of a Turtle program: load the tools, make a turtle, tell it to move, finish. Everything below explains a program you have already seen work.

Tip

You can read, predict and trace every program on this page from a phone. Actually running Python needs a computer where you are allowed to install it. If you only have a phone, keep going: predicting what a program will draw is the skill this lesson is really about.

Moving the Turtle

A Turtle program always follows the same four steps: import the turtle tools, create a turtle to control, draw with it, then finish. Here is the starter code that does the first two steps and takes one small step forward.

import turtle

wn = turtle.Screen()
wn.bgcolor("light green")
wn.title("Turtle")
skk = turtle.Turtle()
skk.forward(100)
turtle.done()

The first line loads all of Turtle's features. The next three lines open a drawing window, colour its background and give it a title. Then skk = turtle.Turtle() creates the robot itself and names it skk. You could call it anything you like. The line skk.forward(100) moves it 100 pixels in the direction it is facing, and turtle.done() keeps the window open so you can admire your work.

Once you have a turtle, a handful of commands cover most of what you need. In each row below, skk is just the name we gave our turtle.

CommandWhat it doesExample
forward(amount)move ahead by that many pixelsskk.forward(100)
backward(amount)move back without turningskk.backward(200)
right(angle)turn clockwise on the spotskk.right(90)
left(angle)turn anticlockwise on the spotskk.left(120)
goto(x, y)jump to an exact positionskk.goto(-140, 140)
penup()lift the pen so moving leaves no lineskk.penup()
pendown()put the pen back down to draw againskk.pendown()
shape(name)change the marker, such as "turtle" or "arrow"skk.shape("turtle")
color(name)change the pen colourskk.color("blue")

To draw a triangle, you repeat the same pair of moves three times: go forward, then turn. A triangle has three equal outside turns of 120 degrees, so the pattern is forward, turn left 120, three times over.

import turtle

skk = turtle.Turtle()
skk.forward(100)
skk.left(120)
skk.forward(100)
skk.left(120)
skk.forward(100)
skk.left(120)
turtle.done()

A square is the same idea with four sides and four right-angle turns of 90 degrees: forward, turn left 90, four times over. Notice how much of that code is copied and pasted. That repetition is exactly what loops will tidy up in a later lesson.

Variables: a named container

A variable is a named container that holds a piece of information. Every variable has two parts: a name, so you can refer to it, and a value, the data it currently holds. You create one by writing the name, an equals sign, then the value.

age = 15
message = "Happy birthday!"

Here age is a number and message is a string, which is the programming word for text. Text always goes inside quotation marks so Python knows it is words and not an instruction. Variables can hold more than numbers and words: you have already stored one without noticing, because skk = turtle.Turtle() puts your whole turtle into a variable called skk.

The value inside a container can change while the program runs. On your birthday you might want to move from 15 to 16. You can set the new value directly, or you can build it out of the old one:

age = 15
age = age + 1

Read the second line from the right: Python first works out age + 1, which is 16, and only then stores that result back into age. This pattern, taking the current value and putting an updated one back, comes up constantly, so it is worth getting comfortable with now.

Tip

When you see x = x + 1, do not read it as a claim that something equals itself plus one. Read the right side first, work out the answer, then let the arrow point left: the new value replaces the old one in the container.

A worked example: what does Turtle draw?

Because a variable's value can change, you cannot know what a program does just by reading names. You have to track each value as you go. Try this puzzle by hand before you run it. The turtle starts at the centre, position (0, 0), facing right.

import turtle

t = turtle.Turtle()
length = 100
angle = 90
t.forward(length)
angle = angle + 90
t.left(angle)
t.forward(length)
t.forward(length)
length = length - length
t.forward(length)
t.right(angle)
length = 100
t.forward(length * 2)

Follow the values step by step. length is 100 and angle is 90. The first t.forward(length) moves 100 to the right, so the turtle is now at (100, 0). Next, angle = angle + 90 makes angle become 180. The turn t.left(180) spins the turtle a half circle, so it now faces left. The next two t.forward(length) calls move it 100, then another 100, back to (0, 0) and on to (-100, 0).

Then length = length - length sets length to 0, so the following t.forward(0) does nothing at all. The turn t.right(180) faces the turtle right again. Finally length is reset to 100, and t.forward(length * 2) moves 200, from (-100, 0) all the way across to (100, 0).

The result is a single straight horizontal line, drawn back and forth between (-100, 0) and (100, 0). No triangle, no square, just a line. The lesson is that the same variable name meant five different things at different moments, and only careful tracking reveals the shape.

When it breaks: reading an error

Programs fail in ordinary ways, and the error message usually names the problem. Read this version and decide what goes wrong before you read on.

import turtle

pen = turtle.Turtle()
pen.forward(distance)
turtle.done()

Python stops at the fourth line and reports:

NameError: name 'distance' is not defined

Tip

distance was never given a value, so there is no container by that name to read from. Python is not confused about drawing, it is confused about a name. The fix is one line: put distance = 80 above it. When you meet an error, read the last line first, find the line number it names, then ask which name or value it could not find.

Nothing here needs a computer. Naming the failing line, saying why it failed and proposing the smallest fix is the same reasoning you would use with Python open in front of you.

Go further, if you want to run it

Want to watch these programs draw on your own machine? An optional annex walks through installing Python and IDLE, running a supplied starter file, breaking it on purpose and fixing it. It needs a computer you are allowed to install software on, and it is not required for anything later in the course.

Go further: real Python on your computer

Check yourself

  1. A turtle starts in the middle of the screen facing right. Which single command turns it to face straight up, and by how many degrees?
  2. In your own words, what are the two parts every variable has, and what is each one for?
  3. If a variable holds count = 4 and the next line is count = count + 3, what value does count hold afterwards, and why do you read the right side first?
Educator guidance · 60 min

Prepare

  • Download the supplied working and broken Python files and keep them available locally
  • Preflight condition for the 60-minute route: confirm Python 3, IDLE, Turtle and both starter files work on the devices before learners arrive
  • Print one tracing and debugging sheet per learner or pair

Materials

  • One computer for each learner or pair
  • Python 3 with IDLE and Turtle
  • Supplied starter and broken files
  • Tracing/debugging worksheet and pens
  • Projector optional

Facilitate

  • Do not run changed code until learners have recorded a prediction
  • When code fails, ask for the last error line, failing line and one hypothesis before offering a fix
  • Change one variable or line at a time so cause and effect remain visible
  • Accept an incorrect prediction when the learner compares it honestly and revises
  • If some devices fail, pair learners on working computers; learners waiting for a keyboard become navigators or test leads using the print sheet. Rotate them onto a working device at the baseline, debugging and creation milestones instead of repairing machines one by one during the lesson
  • Treat an administrator-blocked device as unavailable, not as learner failure; pause everyone only when the same fault affects many devices

Discussion

  • Which line caused the visible change, and which behavior stayed unchanged?
  • What did the final line of the NameError tell you to inspect?
  • What did you change after observing your first personal drawing?

Suggested introduction

Ask one learner to act as the Turtle while another gives only forward and turn instructions. Connect ambiguity in human instructions to precise code, then require a prediction before the first changed run.

Likely misconception

Running again without forming a hypothesis is not debugging. Learners should connect one observed symptom to one small testable change.

Expected response

Learners should reach a visible first run, commit a movement prediction, compare it with output, explain the effect of one variable, repair the inconsistent name and create a small personal drawing.

Adaptation

Individuals complete every role themselves. In pairs, the driver types and runs; the navigator predicts, traces, reads errors and proposes the next single test. Swap after the baseline, debugging repair and first creation run. Ask the driver to explain the navigator's proposal before typing so one confident learner cannot take over. For a projector group, collect predictions before execution.

Extension

Add a second named variable, use `penup()` and `goto()` to start a separate shape, or refactor one repeated shape into a function after the learner reaches the later functions lesson.

Shorten it

35-minute timed route (devices must be ready): 0-5 baseline run; 5-10 predict and observe; 10-15 modify distance; 15-23 diagnose and repair NameError; 23-32 make and run a three-move personal mark; 32-35 record one cause-and-effect reflection. It omits installation troubleshooting, extended discussion, colour polish, a second creation revision and the full debrief.

Debrief

  • Where did prediction save you from random trial and error?
  • How did the error category narrow the search?
  • Which choice made your final drawing yours?

Group adaptations

Pairs
Driver types and runs. Navigator predicts, traces, reads errors and proposes one test. Swap after the baseline, debugging repair and first creation run, not after every click.
Small groups
Use pairs at working devices. An extra learner becomes test lead, records prediction and result, and must propose the next single change before the driver types it.
Whole class
Project the code when available, collect predictions without voting on popularity, run once, then ask learners to cite the controlling line. If projection fails, use the printed code and one working device for milestone runs.

Setup and troubleshooting

  • Python not found: try `py` on Windows, confirm Python 3 installation, then reopen the terminal
  • Wrong file runs: save, read the filename in the editor title and use Run Module again
  • Syntax or indentation error: read the line number, compare punctuation and leading spaces, then change one line
  • Turtle window missing or frozen: use desktop Python/IDLE, retain `turtle.done()`, close the previous Turtle window before rerunning
  • Copied punctuation behaves strangely: retype quotation marks and minus signs in the editor

Found something unclear, outdated or improvable? Suggest an improvement

Where this lesson comes from

Built from

  • Programming in a Data World: Lecture 1 deck (Turtle + variables)
  • Programming in a Data World: Lecture Notebook (Turtle methods)

alphaPlan courses are built from taught programmes rather than invented for the web. Where a claim rests on an outside standard or a reported case, it is named above so you can check it rather than take our word for it.

This course was developed by alphaPlan Center from programs delivered in partnership with the American Corners network.

Found something unclear, outdated or improvable? Suggest an improvement