18 Sep turtle.xcor() function in Python
The turtle.xcor() function in Python returns the turtle’s current x-coordinate. Useful for getting the turtle’s position for calculations.
Syntax: turtle.xcor()
Parameters: None.
Let us see an example to implement the turtle.xcor() function in Python:
Demo16.py
# turtle.xcor() function in Python
# Code by Studyopedia
import turtle
window = turtle.Screen()
t = turtle.Turtle()
print("Initial x coordinate:", t.xcor())
t.forward(100)
print("After moving forward 100:", t.xcor())
window.exitonclick()
The following is the output:

In the above code, we followed the below steps:
- Import the module: import turtle loads Python’s turtle graphics library.
- Create the screen: window = turtle.Screen() opens the drawing window.
- Create the turtle: t = turtle.Turtle() creates the turtle you’ll control.
- Print initial x: print(“Initial x coordinate:”, t.xcor()) outputs the turtle’s current x-position. By default, it starts at (x = 0).
- Move forward: t.forward(100) moves the turtle 100 units along its current heading. Starting facing east, this increases (x) by 100 (drawing a line since the pen is down by default).
- Print new x: print(“After moving forward 100:”, t.xcor()) prints the updated x-position, which will be 100 if starting from the origin facing east.
- Close on click: window.exitonclick() keeps the window open until you click, then closes.
If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
- OpenCV Tutorial
- Python Tutorial
- NumPy Tutorial
- Pandas Tutorial
- Matplotlib Tutorial
- Generative AI Tutorial
- LangChain Tutorial
- RAG Tutorial
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- Copilot Tutorial
- Gemini Tutorial
- ChatGPT Tutorial
No Comments