Back to: Python Programming
Match-case statement (switch): An alternative to using many ‘elif’ statements. Code is executed is a value matches a ‘case’.
Benefits: cleaner code with more readable syntax.
A match statement takes an expression and compares its value to successive patterns given as one or more case blocks.
Specifically, pattern matching operates by:
- using data with type and shape (the subject)
- evaluating the subject in the match statement
- comparing the subject with each pattern in a case statement from top to bottom until a match is confirmed.
- executing the action associated with the pattern of the confirmed match
If an exact match is not confirmed, the last case, a wildcard “_” (underscore), if provided, will be used as the matching case. If an exact match is not confirmed and a wildcard case does not exist, the entire match block is a no-op.
Below we a function with one parameter (day) – (day) will be a number 1 – 7, the function will return the day of the week.
def day_of_week(day):
if day == 1:
return "It is a Sunday"
elif day == 2:
return "It is a Monday"
elif day == 3:
return "It is a Tuesday"
elif day == 4:
return "It is a Wednesday"
elif day == 5:
return "It is a Thursday"
elif day == 6:
return "It is a Friday"
elif day == 7:
return "It is a Saturday"
else:
return "Not a valid day"
print(day_of_week(3))
An alternative way to achieve the same output that is cleaner and easier to read is to use a match case:
def is_weekend(day):
match day:
case "Sunday":
return True
case "Monday":
return False
case "Tuesday":
return False
case "Wednesday":
return False
case "Thursday":
return True
case "Friday":
return False
case "Saturday":
return True
case _:
return False
print(is_weekend("Sunday"))
There is a lot of repetition here, we can use the OR logical operator “| = or” to clean up this code:
def is_weekend(day):
match day:
case "Saturday" | "Sunday":
return True
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return False
case _:
return False
print(is_weekend("Monday"))