match case statement in Python
The match-case statement in Python, is similar to a switch-case in other languages like C, Java, or JavaScript. This feature was introduced in Python 3.10.
Basic Syntax
Python
match variable:
case value1:
# Code block for value1
case value2:
# Code block for value2
case _:
# Default case (like else) Explanation:
- match variable: You check the value of the variable.
- case value: If variable == value, this block executes.
- case _: Acts as the default case (executed if no other cases match).
Example: Simple Match-Case.
Python
# Example: Day of the week
day = "Monday"
match day:
case "Monday":
print("Start of the work week!")
case "Friday":
print("Almost weekend!")
case "Saturday" | "Sunday": # Multiple values in one case
print("Weekend!")
case _:
print("Midweek day") Output: Start of the work week!
Explanation:
- "Saturday" | "Sunday": Matches either "Saturday" or "Sunday".
- _ : Matches anything else (default case).