Python Switch Statement

09 Feb 2014

Python has no switch statement. Period.

To achieve switch-like statement, one direct way is to use if - elif - else block.

However, there are other alternatives than just plain, and possibly a bit more verbose if - elif - else way. You can use python dictionary to do that, here is an example:

def f(x):
    return {
        'a': 1,
        'b': 2,
        }.get(x, 9)    # 9 is default if x not found

Personally I think it is more elegant and succinct code than plain if-else. See this stackoverflow thread.