← Back to Blog

match / case — The Full Picture

The idea!

You've covered match / case, guards, and pattern matching.

This is your reference. Everything in one place.

Come back here whenever you need a reminder.

match / case — the basics

match command:
    case "quit":
        print("Quitting.")
    case "help":
        print("Help.")
    case "start" | "run":
        print("Starting.")    # | combines multiple values
    case _:
        print("Unknown.")     # wildcard — always last

One variable. Many cases. First match wins. case _ catches everything else.

Guards — conditions inside cases

match score:
    case n if n >= 90:
        print("Excellent.")
    case n if n >= 70:
        print("Good.")
    case n if n >= 60:
        print("Passed.")
    case _:
        print("Failed.")

n captures the value. The guard adds the condition. Both must be true for the case to run.

Normalize before matching

match command.lower():    # normalize first
    case "quit":
        print("Quitting.")

match is case-sensitive. Always normalize strings before matching.

match vs if / elif

# match — one variable, many values
match product:
    case "water":   price = 1.00
    case "coffee":  price = 2.00
    case _:         price = None

# if / elif — complex, multi-variable logic
if score > 90 and attendance > 80:
    print("Honours.")

Use match when checking one variable. Use if / elif for complex logic involving multiple variables.

Common Mistakes

  • match requires Python 3.10+ — check your version
  • Always add case _ — unmatched values are silently ignored
  • Normalize with .lower() before matching strings
  • case _ always goes last — it matches everything
  • Use match for one variable — if / elif for complex logic

What you should understand now

  • match checks one value against multiple cases — first match wins
  • case _ is the wildcard — always last, catches everything
  • | combines multiple values in one case
  • Guards add conditions — case n if n > 0
  • match is available from Python 3.10+ only
[ login to bookmark ] // copied! 21 views · 1 min
// resources
Cheatsheet match / case — The Full Picture
← prev Common MATCH/CASE Mistakes next → When one loop isn't enough
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.