What is the match-case statement used for in Python?
Answer:
Explanation:
The match-case
statement in Python is used for matching specific patterns in values, providing a way to perform pattern matching. Introduced in Python 3.10, it allows you to compare a value against several patterns and execute the corresponding block of code for the first pattern that matches.
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case _:
return "Unknown status"
In this example, the match-case
statement checks the value of status
and returns a corresponding message based on the matched case. The underscore (_
) acts as a wildcard, matching any value that doesn’t match any of the other cases.
The match-case
statement is a powerful tool for simplifying complex conditional logic, particularly when dealing with multiple potential values or patterns. It enhances code readability and maintainability by allowing you to express different cases in a clear and concise way.