Predictive Hacks

The switch case statement in Python

Now, with Python 3.10, we are able to write to switch statements like that in Java and R. The structure of the “switch case” statement in Python is the following.

match subject:
    case <pattern_1>:
    case <pattern_2>:
    case <pattern_3>:
    case _:

Note that it uses the “match” keyword instead of the “switch” and it takes an expression and compares its value to successive patterns in case blocks. If an exact match is not found, we can use the last case with the wildcard, i.e. _, which is the “default”, where it works like the else statement. If an exact match is not found and we have not used a wildcard case, then the entire match block is a no-op.

We can write a function that contains the “switch” statement. For example:

def my_erros(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case 401 | 403 | 404:
            return "Not allowed"
        case _:
            return "Something's wrong with the internet"

A common example of the “switch case” is for returning the weekdays by taking as input the weekday number. For example:

def my_weekday(day):
    match day:
        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 "Invalid day number. Try again"


Finally, we can use lists and tuples if we want to match multiple patterns.

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s