How do you undo the turtle’s last action?
To undo the turtle's last action in Python, you can use the turtle.undo()
function. This function reverts the turtle's state back to the previous state, effectively undoing the last action performed.
Take an example to use the turtle.undo()
function:
import turtle
# Create a turtle object
t = turtle.Turtle()
# Move the turtle forward
t.forward(100)
# Undo the last action
t.undo()
# Move the turtle backward
t.backward(50)
# Undo the last action again
t.undo()
# Close the turtle graphics window
turtle.done()
Exaplanation:
turtle
module and create a turtle object called t
.forward()
method with a distance of 100. After that, we use the undo()
function to undo the last action, which was moving forward. This brings the turtle back to its initial position.backward()
method with a distance of 50. Again, we use the undo()
function to undo the last action, which was moving backward. This brings the turtle back to its initial position once more.turtle.done()
function.turtle.undo()
function, you can easily undo the turtle's last action and revert its state to a previous point in the drawing.