Basic Structure of a Python Turtle Program


import turtle

# Set up the screen
screen = turtle.Screen()
screen.title("Move the Square with Keys: n, s, e, or w")
screen.setup(width=600, height=600)

# Create a turtle to represent the square
square = turtle.Turtle()
square.shape("square")
square.color("blue")
square.penup()  # Prevent the turtle from drawing lines

# Movement functions
def move_north():
    y = square.ycor()
    square.sety(y + 20)

def move_south():
    y = square.ycor()
    square.sety(y - 20)

def move_east():
    x = square.xcor()
    square.setx(x + 20)

def move_west():
    x = square.xcor()
    square.setx(x - 20)


# Key bindings
screen.listen()
screen.onkey(move_north, "n")
screen.onkey(move_south, "s")
screen.onkey(move_east, "e")
screen.onkey(move_west, "w")

# Keep the window open
screen.mainloop()