Python match + case

writing match + case instead of if + elif + else
2025-11-04 13:15
// updated 2025-11-05 22:18

Instead of writing the if ... elif ... else structure, we can use the match ... case structure, especially if the comparison operators are just looking at one variable but several discrete values:

match my_variable
  case 1:
    # do 1 stuff here
  case 2:
    # do 2 stuff here
  case 3 | 4:
    # do 3 or 4 stuff here
  case _:
    # do default stuff here

This match-case structure (similar to a switch-case structure in other programming languages) contrasts with the if-else structure:

if my_variable == 1: 
  # do 1 stuff here 
elif my_variable == 2:
  # do 2 stuff here
elif my_variable == 3 or my_variable == 4:
  # do 3 or 4 stuff here
else
  # do other stuff here

While the if ... elif ... else structure might have fewer lines of code, each line feels "lighter" and "neater" with the match ... case structure, perhaps because it eliminates the unnecessary repetition of the variable name!

⬅️ older (in textbook-python)
🐍 Python branching (if + else + elif)
newer (in textbook-python) ➡️
Python looping (for + while) 🐍
⬅️ older (in code)
🐍 Python branching (if + else + elif)
newer (in code) ➡️
Python looping (for + while) 🐍
⬅️ older (posts)
🐍 Python branching (if + else + elif)
newer (posts) ➡️
Python looping (for + while) 🐍