How does the wildcard pattern (_) work in a match-case statement?

How does the wildcard pattern (_) work in a match-case statement?

a) It matches no patterns
b) It matches any pattern
c) It matches only strings
d) It throws an error

Answer:

b) It matches any pattern

Explanation:

In a match-case statement, the underscore (_) acts as a wildcard pattern that matches any value. It is typically used as the last case to handle all remaining cases that do not match any of the previous patterns.

def handle_status(status):
    match status:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case _:
            return "Unknown status"

In this example, the wildcard pattern _ ensures that the function returns “Unknown status” for any status code that isn’t explicitly handled by the other cases.

The wildcard pattern is useful for creating fallbacks or default behavior in your pattern matching logic, ensuring that your code can gracefully handle unexpected or undefined inputs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top