I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a switch
or case
statement, but Python does not appear to have a switch
statement. What are the recommended Python solutions in this scenario?
Python doesn't support switch-case statements. There was a proposal to introduce Python switch case statements in PEP-3103 but it was rejected because it doesn't add too much value. We can easily implement switch-case statements logic using the if-else-elif statements.
Python doesn't have a switch/case statement because of Unsatisfactory Proposals . Nobody has been able to suggest an implementation that works well with Python's syntax and established coding style.
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.
The original answer below was written in 2008. Since then, Python 3.10 (2021) introduced the match
-case
statement which provides a first-class implementation of a "switch" for Python. For example:
def f(x): match x: case 'a': return 1 case 'b': return 2 case _: return 0 # 0 is the default case if x is not found
The match
-case
statement is considerably more powerful than this simple example.
You could use a dictionary:
def f(x): return { 'a': 1, 'b': 2, }[x]
If you'd like defaults, you could use the dictionary get(key[, default])
function:
def f(x): return { 'a': 1, 'b': 2 }.get(x, 9) # 9 will be returned default if x is not found
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