← Back to Blog

One value. Many cases.

The problem...

You have one variable. And ten possible values it could be. So you write ten elif blocks.

It works. But it's long. Repetitive. And harder to read than it should be.

if command == "quit":
    print("Quitting.")
elif command == "help":
    print("Showing help.")
elif command == "start":
    print("Starting.")
elif command == "pause":
    print("Pausing.")
else:
    print("Unknown command.")

Every line repeats command ==. Python can do better.

The idea!

match takes one value and checks it against multiple cases. Cleaner syntax. Same logic. Available from Python 3.10 onwards.

The syntax

match value:
    case option_1:
        # runs if value == option_1
    case option_2:
        # runs if value == option_2
    case _:
        # runs if nothing matched — like else

case _ is the wildcard — it catches everything that didn't match. The equivalent of else.

Your first match

command = input("Enter command: ")

match command:
    case "quit":
        print("Quitting.")
    case "help":
        print("Showing help.")
    case "start":
        print("Starting.")
    case "pause":
        print("Pausing.")
    case _:
        print("Unknown command.")

Same logic as the if / elif chain above. But the variable is named once. Each case is clean and focused.

Matching numbers

import random

roll = random.randint(1, 6)

match roll:
    case 1:
        print("One — try again.")
    case 6:
        print("Six — you win!")
    case _:
        print(f"Rolled {roll} — keep going.")

Multiple values in one case

day = input("Enter a day: ").lower()

match day:
    case "saturday" | "sunday":
        print("Weekend.")
    case "monday" | "tuesday" | "wednesday" | "thursday" | "friday":
        print("Weekday.")
    case _:
        print("Not a valid day.")

The | operator lets you match multiple values in a single case. No need for separate blocks.

Heads up!

  • match is available from Python 3.10 — check your version if it doesn't work
  • case _ is the wildcard — always put it last
  • | combines multiple values in one case
  • Only the first matching case runs — same as if / elif
  • No break needed — unlike some other languages

The mindset shift

Stop thinking: "I need an elif for every possible value."

Start thinking: "One value, many cases — match handles it cleanly."

What you should understand now

  • match checks one value against multiple cases
  • case _ catches everything that didn't match — like else
  • | combines values in a single case
  • First match wins — the rest are skipped
  • Available from Python 3.10 onwards
[ login to bookmark ] // copied! 21 views · 1 min
// resources
Code Example match_case.py
← prev This One's Yours — WHILE next → Not just values — conditions too
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.