← All lessons

match/case

Sign in · Sign up

Lesson 2.8

When you choose by a value rather than by a condition, match is the fit (Python 3.10+):

match command:
    case "start":
        print("Let's go")
    case "stop":
        print("Stop")
    case _:
        print("Unknown command")

Each case is one option. The symbol _ is the fallback: it runs when nothing else matches. Strings in case go in quotes.

command is set by the check. The program prints:

  • Let's go for "start";
  • Stop for "stop";
  • Pause for "pause";
  • Unknown command for anything else.
Hint

In match the options are checked from top to bottom.

Strings in case go in quotes, and the last case _ means "everything else". You no longer write the comparison to "start" with ==.