Switch Statement from Python 3.10
In Python 3.10, A match statement and case statements of patterns with related actions have been added to provide structural pattern matching. Sequences, mappings, primitive data types, and class instances are examples of patterns. Programs can branch on data structures, execute specific actions based on distinct sorts of data, and extract information from complicated data types using pattern matching.
Basic syntax
match status:
case pattern_1:
action_1
case pattern_2:
action_2
case _:
action_wildcard
Example 1 (Getting weekday with switch statement in Python)
def week_day_from_number(number):
match number:
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
case _:
return "Week has only 7 days"
Example 2 (Getting HTTP error from HTTP status code with Switch statement)
def http_error(status):
match status:
case 200:
return "OK"
case 201:
return "Created"
case _:
return "Error"
Top comments (0)