Is there a Python equivalent for the case statement such as the examples available in VB.NET or C#?
What is the replacement of Switch Case in Python? Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.
Python does not have a switch statement functionality. But there are ways to replace the switch statement functionality and make the programming easier and faster. This is possible as Python allows us to create our code snippets that work like Switch case statements in any other language.
You could use a series of if else statements or you could lookup a set of values in a table. You could use an array of function pointers indexed by the character. But there's really no reason to use anything other than the switch statement.
A switch case statement is a multi-branched statement which compares the value of a variable to the values specified in the cases. Python does not have a switch statement but it can be implemented using other methods, which will be discussed below.
In Python 3.10, they introduced the pattern matching.
Example from the Python documentation:
def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case _: return "Something's wrong with the internet"
While the official documentation are happy not to provide switch, I have seen a solution using dictionaries.
For example:
# define the function blocks def zero(): print "You typed zero.\n" def sqr(): print "n is a perfect square\n" def even(): print "n is an even number\n" def prime(): print "n is a prime number\n" # map the inputs to the function blocks options = {0 : zero, 1 : sqr, 4 : sqr, 9 : sqr, 2 : even, 3 : prime, 5 : prime, 7 : prime, }
Then the equivalent switch block is invoked:
options[num]()
This begins to fall apart if you heavily depend on fall through.
The direct replacement is if
/elif
/else
.
However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With