Python Language Alternatives to switch statement from other languages Use what the language offers: the if/else construct.


Well, if you want a switch/case construct, the most straightforward way to go is to use the good old if/else construct:

def switch(value):
    if value == 1:
        return "one"
    if value == 2:
        return "two"
    if value == 42:
        return "the answer to the question about life, the universe and everything"
    raise Exception("No case found!")

it might look redundant, and not always pretty, but that's by far the most efficient way to go, and it does the job:

>>> switch(1)
>>> switch(2)
>>> switch(3)
Exception: No case found!
>>> switch(42)
the answer to the question about life the universe and everything