DEV Community

Shrawan
Shrawan

Posted on • Originally published at pythontherightway.com

Python Pattern Matching -Switch Case

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)