Full lesson Events 3–7 min

Events: When This, Do That!

How does a game know you pressed a key?

Real Python code

This is the code from the video. Read it out loud like a recipe, one line at a time!

wave.py
import turtle

def wave():
    turtle.write("Hi!")
    turtle.forward(40)

turtle.onkey(wave, "space")
turtle.listen()
turtle.done()

Quiz time!

Which key makes jump run?

quiz.py
def jump():
    turtle.forward(50)

turtle.onkey(jump, "Up")
turtle.listen()

Where events hide

Games

Press a key, and your hero jumps

Send buttons

Click Send, and your message goes

Screens

Tap a picture, and it opens up big

Timers

When time is up, the alarm rings

What we learned

The event

  • Something happens
  • A click, a key, a timer
  • Hat block or onkey
VS

The handler

  • The code that answers
  • Waits until it's needed
  • Runs every time

When this happens, do that!

Try it yourself!

In Scratch, make a sprite say hi when you click it, and wave when you press space.

Bit is working on the next one: If / else: pick a path

Liked this quest?

Subscribe to see the next one first! Ask a grown-up before subscribing.

Keep exploring