Switch(Match) Statement in Python
The switch statement is quite popular among those who have programmed in languages like JavaScript, C, or Java. It solves the nightmare of having to write multiple if statements when checking variables. Prior to Python 3.10, the switch case statement or implementation was not built into the language.
Say we need to make different decision based on the day of the week a user selects, a sample multiple if statement might look like this.
[*]Snippet
day = 'Wednesday'
if day == "Monday":
print(f'{day} was selected')
elif day == "Tueday":
print(f'{day} was selected')
elif day == "Wednesday":
print(f'{day} was selected')
else:
print(f'No match found')
[*]Output
Wednesday was selected
Python versions 3.10 and beyond offer the match-case statement, which provides the ability to switch, instead of using the if-else statement.
Syntax: The syntax for the match-case statement looks like this.
match term:
case first-pattern:
action-1
case second-pattern:
action-2
case third-pattern:
action-3
case _:
default-action
Using match-case for the previous example previous example:
[*]Snippet
day = 'Wednesday'
match day:
case 'Monday':
print(f'{day} was selected')
case 'Tuesday':
print(f'{day} was selected')
case 'Wednesday':
print(f'{day} was selected')
case _:
print("This is the default day")
[*]Output
Wednesday was selected
case _: represents the default. This line of the code would be executed when no match is found.
It is possible to match multiple conditions within a single case using the pipe (|) symbol, which serves as a logical ‘or’.
[*]Snippet
day = 'Friday'
match day:
case 'Monday' | 'Friday':
print(f'{day} was selected')
case 'Tuesday':
print(f'{day} was selected')
case 'Wednesday':
print(f'{day} was selected')
case _:
print("This is the default day")
[*]Output
Friday was selected
2.Structural Pattern Matching:
In addition to using the match-case statement to check for a single value, such as a string, integer, or float, it can also be used to match structures and patterns within Python .
Below is the syntax before moving on to a concrete example:
1.[a]: This will match any single item found in a list/tuple
2. case [“a”, “b”]: This will only match a list/tuple having 1st item as ‘a’ and second item as ‘b’ i.e. [“a”,”b”]. It wont match something like
[“a”, “c”], [1,2], etc.3. case [“a”, b]: This will match a list/tuple having first item as ‘a’ while the second item(which could be anything,i.e. int,str,float,list,etc) can be accessed as b in the action section(i.e. body of the case)
4. case [“a”, *b]: This match a list where the 1st item is ‘a’ and the *b means there can be as many postional items as possible folowing the “a” i.e. it matches [“a”, 1], [“a”, 2, 4], [“a”, “d”, “c”], etc.
5.case [“a”, _]: This match any collection(eg. tuple, list, etc) of items that starts with “a”
h
6.case {“name”:name, “age”: age}: This will match a dictionary where the two keys are “name” and “age”. This will match {“name”:”Ray”, “age”:12}, {“age”:20, “name”:”Ray”}. variable name and age can then be accessed7.case {“name”: name}: This match any dictionary having only ‘name’ as the key. It matches {“name”:”Ray”}, {“name”:10}, etc
8.{“name”: name, **a}: This match any dictionary having key as “name” and any other keyword argument(it can be empty). It matches {“name”:”Ray”}, {“name”:”Ray”, “age”:12}, etc
Concrete example: Let’s create a function greet() and pass different kinds of argument
[*]Snippet
def greet(arguments):
match arguments:
case {"name":name, "age": age}:
print(f'Hello {name}, your age is {age}')
case {"name": name}:
print(f'Hello {name}. Age not provided')
case {"age": age}:
print(f'Your age is {age}. Name not captured')
case [a]:
print(f'Captured a list/tuple with one item {a}')
case [a, b]:
print(f'Captured a list/tuple with two items {a} and {b}')
case ["a",b, c]:
print(f"Captured a list/tuple whose 1st item is 'a' and two other items {b} and {c}")
case _:
print("Sorry, no pattern found. Am the default")
[*]Usage
greet({“name”:”Ray”, “age”: 7})
[*]Output
Hello Ray, your age is 7
note:{“name”:name, “age”: age} capture dictionary having only ‘name’ and ‘age’ as keys
[*]Usage
greet({“name”:”Ray”})
[*]Output
Hello Ray. Age not provided
note: {“name”: name} capture only dictionary having ‘name’ as the key. variable name can then be used in the body of the case
[*]Usage
greet({“age”:10})
[*]Output
Your age is 10. Name not captured
[*]Usage
greet([90])
[*]Output
Captured a list/tuple with one item 90
[*]Usage
greet([90,40])
[*]Output
Captured a list/tuple with two items 90 and 40
[*]Usage
greet([“a”, “u”, 9])
[*]Output
Captured a list/tuple whose 1st item is ‘a’ and two other items u and 9
3. Providing a guard:
Sometimes, after a match is found, additional checks are required before proceeding to the body of the ‘case’ statement for further execution. For example, to greet users whose age is above 10.
[*]Snippet
def greet_elder(user_data):
match user_data:
case {"name":name, "age":age} if age>10:
print(f'Hello {name} your age {age} is above 10')
case _:
print("No pattern found")
greet_elder({"name":"Ray", "age": 13})
greet_elder({"name":"New Name", "age": 6})
[*]Output
Hello Ray your age 13 is above 10
No pattern found
4.As pattern
Sometimes when writing a pattern, it may be necessary to check if the pattern matches a particular data type, such as a string, integer, or float, before proceeding to execute the body of the ‘case’.”
[*]Snippet
def detect_type(x):
match x:
case int() as integer:
print("Number captured:", integer )
case str() as string:
print("String captured:", string )
case float() as float_type:
print("Float captured:", float_type )
case dict() as dict_type:
print("Dict captured:", dict_type )
case _:
print("No match found")
detect_type(1)
detect_type(1.0)
detect_type('1')
detect_type({"age":1})
detect_type((1,2))
[*]Output
Number captured: 1
Float captured: 1.0
String captured: 1
Dict captured: {‘age’: 1}
No match found
The match-case statement in Python offers a wide range of possibilities for achieving various tasks.
Hopefully, this guide will provide a starting point for understanding and using the match-case statement in Python.
Thanks for reading and feel free to explore my video collection on YouTube for more educational content. Don’t forget to subscribe to the channel to stay updated with future releases.