In Python, a match-case statement is similar to a switch statement. We use a switch statement to transfer control to a particular block of code based on the value of the tested variable.
Note: Switch statements are an efficient alternative for if-else statements.
Refer Switch Statement in Java
The match-case statement is similar to switch statements in object-oriented languages and is meant to make matching a structure to a case more manageable. It’s more powerful and allows for more complicated pattern matching.
The structure of a match-case is as follows:
match variable:
case matching_value_1: statement_1
case matching_value_2: statement_2
case matching_value_3: statement_3
Let’s look at different examples to understand more.
This example highlights a simple match-case statement.
character = 'A' match character: case 'A': print("character is A") case 'B': print("character is B") case 'C': print("character is C")
We can also use a pipe operator |
to specify multiple values that a case can match.
character = 'M' match character: case 'A' | 'Z': print("character is A or Z") case 'B' | 'D': print("character is B or D") case 'C' | 'M': print("character is C or M")
We can add default cases to the match-case expressions in Python. As Python evaluates against a pattern, we can easily substitute a default case with a disposable underscore (_
).
character = 'V' match character: case 'A' | 'Z': print("character is A or Z") case 'B' | 'D': print("character is B or D") case 'C' | 'M': print("character is C or M") case _: print("Unknown character given")
RELATED TAGS
CONTRIBUTOR
View all Courses