Turtle coordinates: goto() and position()
Turtle coordinates are the x and y numbers for each point in the turtle
window. (0, 0) is the centre, x grows to the right and y grows upwards.
Read Turtle graphics in Python first.
Move to a point with goto()
The window is 800 wide and 600 tall, so x runs from -400 to 400 and y from
-300 to 300. goto(x, y) moves the turtle straight to a point and draws a
line on the way:
import turtle
t = turtle.Turtle()
t.goto(100, 0)
t.goto(100, 100)
t.goto(-100, 100)
print(t.position())
goto() does not turn the turtle. It still faces right at the end.
Read x, y and distance
xcor() and ycor() give one coordinate each. distance(x, y) gives how far
the turtle is from a point.
import turtle
t = turtle.Turtle()
t.goto(30, 40)
print(t.xcor())
print(t.ycor())
print(t.distance(0, 0))
The turtle is 50.0 steps from the centre: 30 across and 40 up.
Point the turtle with setheading()
setheading(angle) points the turtle in an exact direction, whichever way it
faced before. 0 is right (east), 90 is up (north), 180 is left (west)
and 270 is down (south).
import turtle
t = turtle.Turtle()
t.setheading(90)
t.forward(100)
t.setheading(180)
t.forward(50)
print(t.heading())
left() turns from the current direction. setheading() ignores it.
Go back to the start with home()
home() sends the turtle back to (0, 0), facing right. With the pen down it
draws a line on the way back.
import turtle
t = turtle.Turtle()
t.goto(100, 50)
t.setheading(45)
t.home()
print(t.position(), t.heading())
See also: penup() and pendown(), Turtle graphics in Python.
Your turn
Add two lines: draw a line to (60, 80) with goto(), then print how far the
turtle is from (0, 0).
import turtle
t = turtle.Turtle()
# add two lines: go to (60, 80), then print the distance to (0, 0)
Expected output
100.0