What is the match statement in Python?
The match statement was introduced in Python 3.10 which provides a powerful and concise way to implement switch-case-style logic. Unlike traditional if-elif chains. Match
allows pattern matching directly within the language thus making it easier to map specific cases to actions. Each case is defined using the case
keyword within a match block allowing for complex condition handling that is readable and maintainable.
However, not all versions of Python support match
. Versions prior to 3.10 don’t include this feature. For those earlier versions, we can use dictionaries to mimic switch-case functionality, mapping keys to actions. This backward-compatible approach allows developers to achieve similar logic without updating to a newer Python version.
Why Use match or Dictionary Mapping for Switch-Case Logic?
Using match or dictionary mapping allows for more concise and readable code compared to having a multiple if-elif statements especially when handling multiple conditions or cases.
- match provides pattern matching to support complex conditions within fewer lines of code.
- Dictionary-based switching (supported in all Python versions) enables mapping specific keys to actions that provides a workaround for versions without match.
- Both methods improve readability and reduce errors when handling various scenarios or options in applications such as menu selection or command parsing.
How to Implement Switch-Case Logic in Python?
In Python 3.10 or later you can use the match statement for case handling. For earlier versions, dictionary mapping provides a similar effect by associating keys with function references or actions.
Syntax
match variable: case value1: # Action for value1 case value2: # Action for value2 case _: # Default action (like 'else')
Using match (Python 3.10+)
Suppose there is a program that displays a Filipino greeting based on the time of the day in English. The user can input “morning”, “noon”, or “afternoon”, and “evening”.
# Define the time of day time_of_day = "morning" # Use match to select greeting based on the time of day match time_of_day: case "morning": print("Magandang Umaga!") # Good Morning! case "noon": print("Magandang Tanghali!") # Good Noon! case "afternoon": print("Magandang Hapon!") # Good Afternoon! case "evening": print ("Magandang Gabi!") # Good Evening! case _: print("Kamusta?") # How are you?
Using Dictionary Mapping (In case match is not available)
What if we want to have the same the program but don’t have access to the match statement. We can use dictionary mapping.
# Define the greetings for each time of day greetings = { "morning": lambda:print("Magandang Umaga!"), "noon": lambda:print("Magandang Tanghali!"), "afternoon": lambda:print("Magandang Hapon!"), "evening": lambda:print("Magandang Gabi!"), } time_of_day = "morning" greetings.get(time_of_day, lambda:print("Kamusta?"))() # Default greeting