Turtle graphics in Python
Turtle graphics is Python's way to draw: a turtle is a pen you steer with
commands like forward() and left(), and it draws a line wherever it goes.
Make a turtle and move it
import turtle
t = turtle.Turtle()
t.forward(100)
import turtle loads the turtle module. turtle.Turtle() makes a turtle, and
t is its name. The turtle starts in the middle of the window, facing right.
t.forward(100) moves it 100 steps and draws a line behind it.
Turn left and right
left() and right() turn the turtle on the spot. The number is an angle in
degrees: 90 is a quarter turn and 180 turns it right round.
import turtle
t = turtle.Turtle()
t.forward(100)
t.left(90)
t.forward(50)
t.right(90)
t.forward(100)
Turning draws nothing. Only moving draws a line. backward() moves the turtle
the other way without turning it.
Draw a shape one move at a time
Python runs your lines from top to bottom, and the turtle makes its moves in that order. A triangle is three sides with a turn after each one:
import turtle
t = turtle.Turtle()
t.forward(100)
t.left(120)
t.forward(100)
t.left(120)
t.forward(100)
t.left(120)
Each corner turns 120 degrees, not 60. The turtle turns by the angle
outside the corner. Three turns of 120 add up to 360, one full circle.
Ask the turtle where it is
position() gives the turtle's x and y. heading() gives the way it faces,
in degrees: 0 is right and 90 is up.
import turtle
t = turtle.Turtle()
t.forward(100)
t.left(90)
t.forward(50)
print(t.position())
print(t.heading())
It printed (100.00,50.00): 100 steps right and 50 steps up from the middle.
Note: fd(), bk(), lt() and rt() are short names for forward(),
backward(), left() and right(). On this page the finished drawing appears
when the run ends; in the Python editor you watch the turtle move. On your own
computer, end a turtle program with turtle.done() so the window stays open.
See also: Turtle coordinates, Drawing shapes with turtle loops, Printing Output.
Your turn
Finish the step: add two lines that turn the turtle right by 90, then move
it forward 50.
import turtle
t = turtle.Turtle()
t.forward(50)
t.left(90)
t.forward(50)
# add two lines: turn right 90, then move forward 50
print(t.position())
print(t.heading())
Expected output
(100.00,50.00)
0.0