turtle.undo() function in Python

The turtle.undo() function in Python undoes (reverses) the last turtle action. This can be repeated to undo multiple steps, depending on the undo buffer size.

Syntax: turtle.undo()
Parameters: None.

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

Demo11.py

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

import turtle

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

t.forward(100)
t.left(90)
t.forward(50)
t.undo()        # Undo the last action (forward 50)
t.undo()        # Undo the previous action (left 90)

window.exitonclick()

The following is the output:

turtle.undo() 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 (the pen) you control.
  4. Draw first segment: t.forward(100) moves 100 units forward, drawing a line.
  5. Turn left: t.left(90) rotates the turtle 90° counterclockwise without moving.
  6. Draw second segment: t.forward(50) draws a 50-unit line in the new direction.
  7. Undo last action: t.undo() reverses the most recent action, removing the 50-unit forward movement and restoring the prior position.
  8. Undo previous action: t.undo() reverses the earlier left turn, restoring the previous heading.
  9. 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.speed() function in Python
turtle.stamp() function in Python
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment