← Python from Scratch Lesson 25 of 78 · 10 XP

Pattern matching: match

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

When you need to compare one value against many options, a long chain of elif gets clumsy. Since Python 3.10 there's match for this:

command = input()
match command:
    case "start":
        print("Starting")
    case "stop" | "exit":          # | means "or": any of the options
        print("Stopping")
    case _:                        # _ means "everything else"
        print("Unknown command")

match can do much more than compare strings: for example, take lists apart.

match command.split():
    case ["go", direction]:
        print("Going", direction)  # "go north" → Going north
    case _:
        print("?")

Task. Read a game command and reply:

  • start → Game started
  • pause → Paused
  • stop or exit → Game over
  • anything else → Unknown command

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.