- Have You Ever Heard of The Python Match-Case Function?
Match-Case was introduced in Python 3.10 as one of the structural pattern matching functions in conditional statements. Just like if-else, one of the patterns that we often use in conditional statements. Compared to the If-else function, the match-case syntax is more structured and easier to read than if-else.
Match-case was introduced to overcome the shortcomings of the If-else function in handling many conditions, especially when comparing one variable against many possible values.
2. How To Write Match-Case Syntax?
match expression:
case pattern1:
Code block if pattern1 matches
case pattern2:
Code block if pattern2 matches
case _:
The default case (wildcard) if no other pattern matches3. Is Using Match-Case Better Than Using If-Else?
In complex data structures such as tuples, lists, and dictionaries, writing logic with the if-elif function requires writing more code with additional logic, including ‘and’, ‘or’, and ‘len()’. Meanwhile, Match-Case can shorten the writing of logic for complex data forms. In short, Match-case makes the code shorter.
Example:
user = {"role": "admin", "name": "Brian"}If we want to create a greeting sentence based on the user who is logged in, then we need a conditional statement. Here is an example if we use the if-else function:
if "role" in user and user["role"] == "admin":
name = user.get("name", "Unknown")
print(f"Hello Admin {name}")
elif "role" in user and user["role"] == "user":
name = user.get("name", "Unknown")
print(f"Hello User {name}")
else:
print("Role is not recognized")With Match-Case, we don’t need to write the logic of operations or comparison operators, but we can write it directly like this:
match user:
case {"role": "admin", "name": name}:
print(f"Hello Admin {name}")
case {"role": "user", "name": name}:
print(f"Hello User {name}")
case _:
print("Role not recognized")4. When Do We Need To Use Match-Case and If-Else?
If you want to create a neater code structure within conditions where limited value options are directly mentioned, such as for a menu, status code, or dispatcher.
Meanwhile, if-else is used for logical expressions that are capable of evaluating logical conditions and validating input, but require longer structural code.
5. So, How Does Match-Case Work?
Get Sheyla Annisyah’s stories in your inbox
Join Medium for free to get updates from this writer.
When Python finds a match, it matches the value of the variable against each case. Once it matches, the associated block is executed, then stops (without a break). This makes it ideal for code that requires choosing between many directly stated conditions.
Example:
color = "red"
match color:
case "red":
print("Stop")
case "yellow":
print("Caution")
case "green":
print("Go")
case _:
print("Unknown color")6. When Not to Use Match-Case?
If the condition involves a logical expression (for example, age > 60), match case is not appropriate.
age = 65
match age:
case 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | \
76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | \
92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100:
print("Senior Citizen")
case _:
print("Not a Senior Citizen")Instead of using match-case, we can simply use the if-else statement.
age = 65
if 60 <= age <= 100:
print("Senior Citizen")
else:
print("Not a Senior Citizen")7. Case Study: Hospital Patient Data Information System
In a hospital patient data management system, match-case statements are utilized to efficiently handle main menu and submenu navigation options.
Key strengths of this approach:
- Provides a cleaner and more modular way to manage menu options.
- Easily extendable as the number of menu options grows.
Example:
# Displaying the Hospital Patient Data Menu
def main():
while True:
print("\n" + "=" * 10 + " HOSPITAL PATIENT DATA MENU " + "=" * 10)
print("1. View Hospital Patient Data")
print("2. Add Hospital Patient Data")
print("3. Edit Hospital Patient Data")
print("4. Delete Hospital Patient Data")
print("5. Exit")
print("=" * 50 + "\n")
try:
selected_menu = int(input("Please select a menu (1–5): "))
match selected_menu:
case 1:
menu_view()
case 2:
menu_add()
case 3:
menu_edit()
case 4:
menu_delete()
case 5:
print("Thank you!")
break
case _:
print("\n-- Invalid Option! Please choose between (1–5) --")
except ValueError:
print("\n-- Input must be a number! --")Conclusion
Match-Case is a modern Python feature that enhances the structure and readability compared to if-else, especially when dealing with discrete conditions. However, it doesn’t fully replace if-else, as it’s not suitable for logical expressions or dynamic comparisons. Choosing between the two depends on the specific context of the problem you’re trying to solve.
Author: Reza Afriansyah & Sheyla Annisyah
This work was created as part of an assignment completed collaboratively for:Purwadhika Digital Technology School
Lecturer: Median Hardiv Nugraha






