What happens if no case matches in a match-case statement?
a) The first case is executed
b) An error is thrown
c) The default case is executed if present, otherwise nothing
d) The program exits
Answer:
c) The default case is executed if present, otherwise nothing
Explanation:
If no case matches in a match-case
statement, the default case (often represented by the wildcard pattern _
) is executed if it is present. If there is no default case, nothing happens, and the program continues execution after the match statement.
command = "pause"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case _:
print("Unknown command") # This line is executed because "pause" does not match any other case
This behavior allows you to provide fallback logic in your programs, ensuring that your code can handle unexpected or unsupported inputs gracefully.
Without a default case, the match-case
statement would simply skip over any unmatched cases, which could be appropriate in situations where unmatched inputs are intentionally ignored.