The Python Match Statement
A match statement chooses what to do based on the value it is given.
When you would otherwise need many if..else statements, match can take their place.
Out of several code blocks, it picks one to run.
Here are the steps:
- Python evaluates the
matchexpression one time. - It then compares the result against the value of each
case. - When a value matches, the block of code under that case runs.
In the example below, a weekday number decides which day name gets printed:
Example
Prompt
Write a Python program that uses a match statement to print the weekday name based on a day number.
Set day to 4 and match cases 1-7 to Monday-Sunday.
Output: complete Python program
main.py
day = 4
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
Syntax
main.py
match expression:
case x:
code block
case y:
code block
case z:
code block
Default Value
To run a block when no other case has matched, finish with a case whose value is the underscore character _.
Since _ matches anything, its position matters: only as the last case does it act as a default.
Example
Prompt
Write a Python program that uses a match statement with a default case using underscore _.
Set day to 4, match 6 for Saturday, 7 for Sunday, and _ for the default message.
Output: complete Python program
main.py
day = 4
match day:
case 6:
print("Today is Saturday")
case 7:
print("Today is Sunday")
case _:
print("Looking forward to the Weekend")
Combine Values
One case can test for several values. Separate them with the pipe character |, which acts as an "or" here:
Example
Prompt
Write a Python program that uses the pipe | operator in match cases to combine multiple values.
Match days 1-5 as weekday and 6-7 as weekend.
Output: complete Python program
main.py
day = 4
match day:
case 1 | 2 | 3 | 4 | 5:
print("Today is a weekday")
case 6 | 7:
print("I love weekends!")
If Statements as Guards
A case can carry an extra condition too. Just add an if statement after its values:
Example
Prompt
Write a Python program that uses if guards in match case statements.
Match weekday patterns with month conditions for April and May.
Output: complete Python program
main.py
month = 5
day = 4
match day:
case 1 | 2 | 3 | 4 | 5 if month == 4:
print("A weekday in April")
case 1 | 2 | 3 | 4 | 5 if month == 5:
print("A weekday in May")
case _:
print("No match")