Switch states are a really useful tool for structured pattern matching. From Python 3.10 onwards it is supported using the match - case statement.
match expression: case value1: # Code executed if expression matches value1 break case value2: # Code executed if expression matches value2 break # ... (additional cases) case _: # Code executed if no case matches
When a switch statement is encountered, the expression value is evaluated once. Each case constant is compared against the expression value. Upon finding a match, the corresponding code block is executed until a break statement is encountered or the switch statement concludes. If none of the cases match the expression value, the code within the _ case is executed.
value = 'case2'
match value:
case 'case1':
print('This is case 1')
case 'case2':
print('This is case 2')
case 'case3':
print('This is case 3')
case _:
print('This is the default case')
What are switch statements?
When would you use switch statements?
Switch statements < Python 3.10
Before Python 3.10 was released there wasn't a switch statement, so programmers had to emulate it using if statements.
value = 'case2'
if value == 'case1':
print('This is case 1')
elif value == 'case2':
print('This is case 2')
elif value == 'case3':
print('This is case 3')
else:
print('This is the default case')
How many cases can a switch statement have?
How do you define multiple cases in a switch statement in Python?
7. The statement is used when there are multiple possible cases and a different action needs to be taken for each case.