turtle.heading() function in Python

The turtle.heading() function in Python returns the turtle’s current heading (angle it is facing) in degrees. 0 is east, 90 is north, 180 is west, 270 is south.

Syntax: turtle.heading()
Parameters: None.

Let us see an example to implement the turtle.heading() function in Python:

Demo15.py

# turtle.heading() function in Python
# Code by Studyopedia

import turtle

window = turtle.Screen()
t = turtle.Turtle()

print("Initial heading:", t.heading())  # Get current heading
t.left(45)
print("After turning left 45 degrees:", t.heading())

window.exitonclick()

The following is the output:

turtle.heading() function in Python

In the above code, we followed the below steps:

  1. Import the module: import turtle loads Python’s turtle graphics library.
  2. Create the screen: window = turtle.Screen() opens the drawing window.
  3. Create the turtle: t = turtle.Turtle() creates the turtle you’ll control.
  4. Compute angle to a point: angle = t.towards(100, 100) calculates the absolute heading (in degrees) from the turtle’s current position to the point (100, 100). It does not move the turtle; headings are measured with 0° to the right (east) and increasing counterclockwise.
  5. Print the angle: print(“Angle to point (100, 100):”, angle) displays that computed heading in the console.
  6. Move to the point: t.goto(100, 100) moves the turtle directly to coordinates (100, 100), drawing a straight line if the pen is down (default).
  7. Close on click: window.exitonclick() keeps the window open until you click inside it, 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:

turtle.towards() function in Python
turtle.xcor() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment