DEV Community

Shrawan
Shrawan

Posted on • Originally published at pythontherightway.com

1 1

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay