match and case
match compares one value with a list of patterns. Each pattern is written after the word case. Python runs the branch whose pattern matches the value. This statement was added in Python 3.10.
day = 2
match day:
case 1:
message = "Monday"
case 2:
message = "Tuesday"
case _:
message = "Invalid day"
print(message)
Output:
Tuesday
Here day is 2. It matches case 2, so message becomes "Tuesday". The _ pattern matches any value. It works like an else at the end.
If several values should share one branch, join them with |, as in case 6 | 7:. Use match when you compare one value with exact values. For ranges, like "20 or more", or for conditions that check different things, use if and elif.
In the exercise, finish a simple calculator with match.