Python Docs

Match Case

Instead of writing many if..else statements, you can use the match statement.

The match statement selects one of many code blocks to be executed.

Why Use match-case?

match-case makes code:

  • Cleaner
  • Easier to read
  • Better for handling multiple possibilities
  • Suitable for pattern-based decisions

It is especially helpful when:

  • Comparing against many possible values
  • Working with structured data (like tuples or dictionaries)
  • Replacing long chains of if-elif-else statements

Syntax

match expression:
  case x:
    code block
  case y:
    code block
  case z:
    code block

This is how it works:

  • The match expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.

The example below uses the weekday number to print the weekday name:

Example

day = 4
match day:
  case 1:
    print("Monday")
  case 2:
    print("Tuesday")
  case 3:
    print("Wednesday")
  case 4:
    print("Thursday")
  case 5:
    print("Friday")
  case 6:
    print("Saturday")
  case 7:
    print("Sunday")

Output:

Thursday