Using match-case
in Python
As I already mentioned in the about section, I am learning Python. In this series I wil cover Python basics. Enjoy!
Python, introduced in version 3.10, has added a powerful control flow structure: match-case
. This structure, similar to switch-case statements in other languages, allows for more readable and efficient handling of multiple conditions. Let's explore how to use match-case
in Python.
Basic Syntax
The basic syntax of match-case
in Python is straightforward. Here’s an example to demonstrate its usage:
def get_day_message(day):
match day:
case "Monday":
return "Start of the work week!"
case "Tuesday":
return "Second day of the work week!"
case "Wednesday":
return "Midweek already!"
case "Thursday":
return "Almost the weekend!"
case "Friday":
return "Last workday of the week!"
case "Saturday":
return "Weekend fun day!"
case "Sunday":
return "Rest and recharge!"
case _:
return "Invalid day"
In this function, match evaluates the variable day, and case handles each possible value. The underscore _ acts as a default case, similar to the else clause in an if-elif-else statement.
Handling Multiple Cases
You can handle multiple cases that execute the same block of code by grouping them using a tuple:
def get_day_type(day):
match day:
case "Saturday" | "Sunday":
return "Weekend"
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return "Weekday"
case _:
return "Invalid day"
This is useful when you want to group several values that should trigger the same response.
Using Patterns
Python's match-case also supports more complex patterns. Here’s an example using patterns to match different data structures:
def describe_data(data):
match data:
case (x, y) if x == y:
return "A tuple with equal elements"
case [x, y, z]:
return "A list with three elements"
case {"key": value}:
return f"A dictionary with key-value pair, value: {value}"
case _:
return "Unknown structure"
Guard Clauses
You can use guard clauses to add additional conditions to cases. Here’s an example:
def check_age(age):
match age:
case age if age < 18:
return "Minor"
case age if age >= 18 and age < 65:
return "Adult"
case age if age >= 65:
return "Senior"
case _:
return "Invalid age"
Conclusion
The match-case statement in Python is a versatile tool for managing control flow based on pattern matching. It simplifies the code, making it more readable and maintainable, especially when dealing with multiple conditions. Experiment with match-case to see how it can streamline your Python code!
That's it for today!