Search code examples
pythonturtle-graphicspython-turtle

How do I get the turtles position in PythonTurtle


If I made some random movements. How can I get the position of the turtle to go back there?

I tried using some commands like pos() turtle.pos() But it never said the x and y coordinate I use the turtle libary So I type in from turtle import*


Solution

  • You can use the following code for getting the coordinates of the turtle:

    x = turtle.xcor() #For x-coordinate
    y = turtle.ycor() #For y-coordinate
    

    You can store the value in some variables(like x and y).

    Alternatively, if you want to get the coordinates of turtle in the form of a vector, the you can use the .pos() method. Example code:

    pos = turtle.pos() #This returns a 2d vector in the form of (x,y)
    

    To make the turtle go to a certain position, you can use the .goto() method. Example code:

    x = turtle.xcor()
    y = turtle.ycor()
    
    turtle.forward(100)
    turtle.goto(x,y)