What is the syntactical equivalent to switch/case in Python? [duplicate]

We Are Going To Discuss About What is the syntactical equivalent to switch/case in Python? . So lets Start this Python Article.

What is the syntactical equivalent to switch/case in Python?

  1. How to solve What is the syntactical equivalent to switch/case in Python? [duplicate]

    TL;DR
    As of Python 3.10.0 (alpha6 released March 30, 2021), Python has an official syntactical equivalent called match.
    The basic syntax is:
    match value: case condition: action(s) ...

    For older Python versions, there are only workarounds if you don't want to resort to ifelifelse.
    See this excellent community post for a collection of some.
    Example
    my_value = 10 match my_value: case 10: print("The number is ten") case 2*10: print("The number is the double of ten") case 100: print("The number is one hundred") case _: # this is the default handler if none # of the above cases match. print("The number is none of 10, 2*10 or 100")
    Therefore, other answers involving workarounds aren't valid anymore – also from a performance point of view.
    Important Notices
    If coming from languages which support switch and case, it's likely that you already know about their behavior. With Python, there are some differences to note though.
    Cases don't fall through
    It's common that languages with switchcase statements execute every case the value matches – from top to bottom. Hence, there is a third statement – break – to be used in switchcase constructs if you don't want to fall through:
    value = 10 switch (value) { case 10: print("Value is ten"); case 2*5: print("Value is the double of five"); break; case 20/2: print("Value is the half of twenty"); default: print("This is just the default action."); }
    In this example, the first two cases would be executed because the first case falls through. If there was no break statement inside the second case, all cases, including the default one, would be executed.
    In Python, only the first matching case is being executed. You can think of it like every case would contain a hidden break statement.
    Variable references don't work as a condition
    base_color = "red" chosen_color = "green" match chosen_color: case base_color: print("Yes, it matches!")
    This code does actually print that the colors match!
    Bare variable references as case conditions will always match.
    Regardless, literals like case "red": ... and qualified (i.e. dotted) names like case AllColors.red work like expected – no need to be scared of them.
    All of this is the case, because the Python Software Foundation did not decide to just copy another boring control flow model, but to actually implement a fully-fledged pattern matcher which is more than just a switchcase statement. More on this can be found in the next section.
    Powerful Pattern Matching
    matchMatch ain't case hooey
    Specification and information provided in the Python Enhancement Proposals (PEP) nos. 634-636
    In Python, match is actually much more than a simple switch – therefore probably the name. It features special functionality like deep placeholders and wildcards.
    Examples inspired by reading the documentation – so you don't have to:
    match point: case (0, 0): print("Origin") case (0, y): print("Our current Y position is", y, " now.")
    You can match arbitrary nested data structures, including placeholders. In the above example, we are matching a tuple with two items where in the second case, we use a placeholder y that gets its value assigned upon matching.
    You can also match class attributes, in a very similar fashion:
    class Point: x: int y: int def location(point): match point: case Point(x=0, y=0): print("Origin is the point's location.") case Point(x=0, y=y): print("The point lies on the y axis at a height of", y, "units.")
    This also explains why you can't match single variable references in case conditions: you don't actually match against the value of that variable but actually introduce a placeholder of that same name!
    Therefore, if you were going to print chosen_color like this:
    base_color = "red" chosen_color = "green" match chosen_color: case base_color: print("Our base color is", base_color)
    It would actually print out
    Our base color is green
    because the base_color is now a placeholder which gets assigned the value of our chosen_color.
    There are a lot more use cases for this advanced pattern matching, an interesting couple of them mentioned in the Python documentation.
    Epilogue
    It will take its time until Python 3.10 gets its deserved adoption. Python 3.10.0 is set to be released stable on October 4, 2021 – meaning it might be included in Ubuntu 22.04 and up.
    If you just want to play around and write programs for yourself, deploy them to your own server, or if you intend to distribute your creations in packaged form and not as plain source code files, give this new feature already a try in your programs – it's going to be a benefit!
    Addendum
    Trying Python 3.10.0
    For Windows and macOS users, this page features the official installer downloads.
    On Debian and Ubuntu, you can use the very popular “DeadSnakes”-project PPA:
    sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update sudo apt install python3.10 python3.10 --version
    Trying Python 3.10.0 without destroying your system
    Docker is an option for using Python 3.10 without any complicated setup steps and in a completely isolated environment.
    docker run -it python:3.10.0a6-alpine
    And that's it. As the time passes by, new alpha or beta versions might be released. You will want to replace the a6 with a different version then.

  2. What is the syntactical equivalent to switch/case in Python? [duplicate]

    TL;DR
    As of Python 3.10.0 (alpha6 released March 30, 2021), Python has an official syntactical equivalent called match.
    The basic syntax is:
    match value: case condition: action(s) ...

    For older Python versions, there are only workarounds if you don't want to resort to ifelifelse.
    See this excellent community post for a collection of some.
    Example
    my_value = 10 match my_value: case 10: print("The number is ten") case 2*10: print("The number is the double of ten") case 100: print("The number is one hundred") case _: # this is the default handler if none # of the above cases match. print("The number is none of 10, 2*10 or 100")
    Therefore, other answers involving workarounds aren't valid anymore – also from a performance point of view.
    Important Notices
    If coming from languages which support switch and case, it's likely that you already know about their behavior. With Python, there are some differences to note though.
    Cases don't fall through
    It's common that languages with switchcase statements execute every case the value matches – from top to bottom. Hence, there is a third statement – break – to be used in switchcase constructs if you don't want to fall through:
    value = 10 switch (value) { case 10: print("Value is ten"); case 2*5: print("Value is the double of five"); break; case 20/2: print("Value is the half of twenty"); default: print("This is just the default action."); }
    In this example, the first two cases would be executed because the first case falls through. If there was no break statement inside the second case, all cases, including the default one, would be executed.
    In Python, only the first matching case is being executed. You can think of it like every case would contain a hidden break statement.
    Variable references don't work as a condition
    base_color = "red" chosen_color = "green" match chosen_color: case base_color: print("Yes, it matches!")
    This code does actually print that the colors match!
    Bare variable references as case conditions will always match.
    Regardless, literals like case "red": ... and qualified (i.e. dotted) names like case AllColors.red work like expected – no need to be scared of them.
    All of this is the case, because the Python Software Foundation did not decide to just copy another boring control flow model, but to actually implement a fully-fledged pattern matcher which is more than just a switchcase statement. More on this can be found in the next section.
    Powerful Pattern Matching
    matchMatch ain't case hooey
    Specification and information provided in the Python Enhancement Proposals (PEP) nos. 634-636
    In Python, match is actually much more than a simple switch – therefore probably the name. It features special functionality like deep placeholders and wildcards.
    Examples inspired by reading the documentation – so you don't have to:
    match point: case (0, 0): print("Origin") case (0, y): print("Our current Y position is", y, " now.")
    You can match arbitrary nested data structures, including placeholders. In the above example, we are matching a tuple with two items where in the second case, we use a placeholder y that gets its value assigned upon matching.
    You can also match class attributes, in a very similar fashion:
    class Point: x: int y: int def location(point): match point: case Point(x=0, y=0): print("Origin is the point's location.") case Point(x=0, y=y): print("The point lies on the y axis at a height of", y, "units.")
    This also explains why you can't match single variable references in case conditions: you don't actually match against the value of that variable but actually introduce a placeholder of that same name!
    Therefore, if you were going to print chosen_color like this:
    base_color = "red" chosen_color = "green" match chosen_color: case base_color: print("Our base color is", base_color)
    It would actually print out
    Our base color is green
    because the base_color is now a placeholder which gets assigned the value of our chosen_color.
    There are a lot more use cases for this advanced pattern matching, an interesting couple of them mentioned in the Python documentation.
    Epilogue
    It will take its time until Python 3.10 gets its deserved adoption. Python 3.10.0 is set to be released stable on October 4, 2021 – meaning it might be included in Ubuntu 22.04 and up.
    If you just want to play around and write programs for yourself, deploy them to your own server, or if you intend to distribute your creations in packaged form and not as plain source code files, give this new feature already a try in your programs – it's going to be a benefit!
    Addendum
    Trying Python 3.10.0
    For Windows and macOS users, this page features the official installer downloads.
    On Debian and Ubuntu, you can use the very popular “DeadSnakes”-project PPA:
    sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update sudo apt install python3.10 python3.10 --version
    Trying Python 3.10.0 without destroying your system
    Docker is an option for using Python 3.10 without any complicated setup steps and in a completely isolated environment.
    docker run -it python:3.10.0a6-alpine
    And that's it. As the time passes by, new alpha or beta versions might be released. You will want to replace the a6 with a different version then.

Solution 1

TL;DR

As of Python 3.10.0 (alpha6 released March 30, 2021), Python has an official syntactical equivalent called match.

The basic syntax is:

match value:
    case condition:
        action(s)
    ...

For older Python versions, there are only workarounds if you don’t want to resort to ifelifelse.
See this excellent community post for a collection of some.

Example

my_value = 10
match my_value:
    case 10:
        print("The number is ten")
    case 2*10:
        print("The number is the double of ten")
    case 100:
        print("The number is one hundred")
    case _:
        # this is the default handler if none
        # of the above cases match.
        print("The number is none of 10, 2*10 or 100")

Therefore, other answers involving workarounds aren’t valid anymore – also from a performance point of view.

Important Notices

If coming from languages which support switch and case, it’s likely that you already know about their behavior. With Python, there are some differences to note though.

  • Cases don’t fall through

    It’s common that languages with switchcase statements execute every case the value matches – from top to bottom. Hence, there is a third statement – break – to be used in switchcase constructs if you don’t want to fall through:

    value = 10
    switch (value) {
        case 10:
            print("Value is ten");
        case 2*5:
            print("Value is the double of five");
            break;
        case 20/2:
            print("Value is the half of twenty");
        default:
            print("This is just the default action.");
    }
    

    In this example, the first two cases would be executed because the first case falls through. If there was no break statement inside the second case, all cases, including the default one, would be executed.

    In Python, only the first matching case is being executed. You can think of it like every case would contain a hidden break statement.

  • Variable references don’t work as a condition

    base_color = "red"
    chosen_color = "green"
    match chosen_color:
        case base_color:
            print("Yes, it matches!")
    

    This code does actually print that the colors match!

    Bare variable references as case conditions will always match.

    Regardless, literals like case "red": ... and qualified (i.e. dotted) names like case AllColors.red work like expected – no need to be scared of them.

    All of this is the case, because the Python Software Foundation did not decide to just copy another boring control flow model, but to actually implement a fully-fledged pattern matcher which is more than just a switchcase statement. More on this can be found in the next section.

Powerful Pattern Matching

matchMatch ain’t case hooey

Specification and information provided in the Python Enhancement Proposals (PEP) nos. 634-636

In Python, match is actually much more than a simple switch – therefore probably the name. It features special functionality like deep placeholders and wildcards.

Examples inspired by reading the documentation – so you don’t have to:

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print("Our current Y position is", y, " now.")

You can match arbitrary nested data structures, including placeholders. In the above example, we are matching a tuple with two items where in the second case, we use a placeholder y that gets its value assigned upon matching.

You can also match class attributes, in a very similar fashion:

class Point:
    x: int
    y: int

def location(point):
    match point:
        case Point(x=0, y=0):
            print("Origin is the point's location.")
        case Point(x=0, y=y):
            print("The point lies on the y axis at a height of", y, "units.")

This also explains why you can’t match single variable references in case conditions: you don’t actually match against the value of that variable but actually introduce a placeholder of that same name!
Therefore, if you were going to print chosen_color like this:

base_color = "red"
chosen_color = "green"
match chosen_color:
    case base_color:
        print("Our base color is", base_color)

It would actually print out

Our base color is green

because the base_color is now a placeholder which gets assigned the value of our chosen_color.

There are a lot more use cases for this advanced pattern matching, an interesting couple of them mentioned in the Python documentation.

Epilogue

It will take its time until Python 3.10 gets its deserved adoption. Python 3.10.0 is set to be released stable on October 4, 2021 – meaning it might be included in Ubuntu 22.04 and up.

If you just want to play around and write programs for yourself, deploy them to your own server, or if you intend to distribute your creations in packaged form and not as plain source code files, give this new feature already a try in your programs – it’s going to be a benefit!

Addendum

Trying Python 3.10.0

For Windows and macOS users, this page features the official installer downloads.

On Debian and Ubuntu, you can use the very popular “DeadSnakes”-project PPA:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.10
python3.10 --version

Trying Python 3.10.0 without destroying your system

Docker is an option for using Python 3.10 without any complicated setup steps and in a completely isolated environment.

docker run -it python:3.10.0a6-alpine

And that’s it. As the time passes by, new alpha or beta versions might be released. You will want to replace the a6 with a different version then.

Original Author edited Oct 5, 2021 at 10:34 Of This Content

Solution 2

Pre-Python 3.10.0 answer

There is not. It is usually done in two ways, depending on the code context:

1. if/elif:

Using the if/elif syntax you can have the most similar version of switch case:

my_value = 10;
if my_value == 10:
    print("The number is ten")
elif my_value == 2*10:
    print("The number is the double of ten")
elif my_value == 100:
    print("The number is one hundred")
else:
    print("The number is none of 10, 2*10 or 100")

2. Dict lookup:

Another less common way, is to make a dict and assign at each condition of the switch/case a corresponding function to be called:

my_value = 10;

def def_action():
    print("The number is none of 10, 2*10 or 100")

def ten_action():
    print("The number is ten")

def double_ten_action():
    print("The number is ten")

def hundred_action():
    print("The number is one hundred")

{
    10: ten_action,
    2*10: double_ten_action,
    100: hundred_action,
}.get(
    my_value,
    def_action # This is the final else, if no match if found
)()

This, despite being less Pythonic, is useful when inside the various cases you have a lot of code that worsen readability.

Original Author Hrabal Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

ittutorial team

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment