Python 3D Academyবাংলা

match and case

🌍 In real life. At a tea stall, the menu has numbers: 1 is tea, 2 is coffee, 3 is juice. When you say "2", the server doesn't ask "is it more than 1? is it less than 3?"; they go straight to the item with that number. Anything not on the menu gets "sorry, we don't have that".

match works like that menu.

The idea in one sentence: match compares one value with each case from the top and runs the first case that matches; case _: catches everything else.

Its words:

  • subject: the value after match
  • case: one option, with a pattern to compare the subject with
  • _ (the wildcard): a pattern that matches anything, like a final else
  • |: inside a pattern, means "or": case "Sat" | "Sun":

Step by step, for match light: when light is "green":

  1. case "red": doesn't match, so Python tries the next case.
  2. case "green": matches, so Python runs print("go").
  3. The rest of the cases are skipped.
light = "green"
match light:
    case "red":
        print("stop")
    case "green":
        print("go")
    case _:
        print("wait")

One case can match several values if you join them with |, which means "or":

day = "Sun"
match day:
    case "Sat" | "Sun":
        print("weekend")
    case _:
        print("weekday")

match or elif? match is neatest when you compare one value with fixed options: menu choices, commands, days. For ranges like age >= 18, or for conditions about different variables, use if/elif.

Like an elif chain, only one case runs: there's no "falling through" into the next case.

Without case _, nothing runs when no case matches. And remember that input() gives text, so compare with "1", not 1:

choice = input("Pick 1, 2 or 3: ")
match choice:
    case "1":
        print("Tea")
    case "2":
        print("Coffee")
    case "3":
        print("Juice")

Mistakes and edge cases.

  • A number case for text. input() gives a str, so case 1: never matches the answer "1". Write case "1":.
  • No case _. If nothing matches, nothing runs, and no error tells you.
  • case _ before other cases. It matches everything, so Python refuses: SyntaxError: wildcard makes remaining patterns unreachable.
  • A bare name as a pattern. case x: doesn't compare with a variable x: it matches anything and stores the subject in x. Before other cases it gives SyntaxError: name capture 'x' makes remaining patterns unreachable.
  • Comparisons in a case. case > 5: gives SyntaxError: invalid syntax. Use if/elif for ranges.

Quiz

  1. What does this print?

    x = "b"
    match x:
        case "a":
            print(1)
        case "b":
            print(2)
        case _:
            print(3)
  2. And with a different value?

    x = "z"
    match x:
        case "a":
            print(1)
        case "b":
            print(2)
        case _:
            print(3)
  3. What does case _: match?

    • Anything that no earlier case matched
    • Only the underscore character
    • Nothing at all
  4. What does this print?

    n = 5
    match n:
        case 1 | 2:
            print("small")
        case _:
            print("other")
  5. This should print two. Which line is wrong?

    c = "2"
    match c:
        case 2:
            print("two")
        case _:
            print("?")

Coding tasks

  1. Ask for a number from 1 to 3, and use match to print the day: 1 is Mon, 2 is Tue, 3 is Wed. Anything else prints Unknown. Remember: input() gives text, so compare with "1", not 1.

  2. Ask for a direction: up, down, left or right. Print the matching arrow, made from keys on your keyboard: ^, v, < or >. Anything else prints ?.