Switch Statement
Python
Python
Published:
Table of content
Switch Statement in Python
Available since Python 3.10.
some_variable = 123
match some_variable:
case 1:
print('got 1')
case 2:
print('got 2')
# This can be a _ if you're not using the variable
case other:
print('got something else', other)
# Other example
class Person:
def __init__(self, name):
self.name = name
values = Person('RIck'), Person('Guido')
for value in values:
match value:
# This is checks if the instance type Person and it requires the instance to have an attribute name with value RIck.
case Person(name='RIck'):
print("I found rick!")
# Also works for built-in types and supports nesting
case Person(name=occupation="Programmer"):
print("I found a programmer")
case Person() as person:
print("I found a person:", person.name)