PythonMatch
Thematch
statement is used to perform different actions based on different conditions.
The Python Match Statement
Instead of writingmanyif..else
statements, you can use thematch
statement.
Thematch
statement selects one of many code blocks to be executed.
Syntax
case x:
code block
case y:
code block
case z:
code block
This is how it works:
- The
match
expression is evaluated once. - The value of the expression is compared with the values of each
case
. - If there is a match, the associated block of code is executed.
The example below uses the weekday number to print the weekday name:
Example
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")
Default Value
Use the underscore character_ as the last case value if you want a code block to execute when there are not other matches:
Example
match day:
case 6:
print("Today is Saturday")
case 7:
print("Today is Sunday")
case _:
print("Looking forward to the Weekend")
The value_ will always match, so it is important to place it as thelastcase to make it behave as a defaultcase.
Combine Values
Use the pipe character| as an or operator in thecase evaluation to check for more than one value match in onecase:
Example
match day:
case 1 | 2 | 3 | 4 | 5:
print("Today is a weekday")
case 6 | 7:
print("I love weekends!")
If Statements as Guards
You can addif
statements in the case evaluation as an extra condition-check:
Example
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")