Python Forum

Full Version: Help: write 'case' with Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I remember in C we can use:
case 0: sentence 0
case 1: sentence 1
case 2: sentence 2
...
Can I write similar sentence with Python? If yes, is there an example code?
Python doesn't have a switch/case construct. The common way of doing something similar is either a chain of if/elif/else, or a dictionary lookup.

So, in C++, you might have:
int lookup(string key) {
    switch (key) {
        case "left": return -1;
        case "right": return +1;
        default: return 0;
    }
}
As an if/elif, you could do this:
def lookup(key: str) -> int:
    if "left" == key:
        return -1
    elif "right" == key:
        return +1
    else:
        return 0
Or, as a dict:
def lookup(key: str) -> int:
    options = {"left": -1, "right": +1}
    return options.get(key, 0)
The second option, with the dict, is not normally used, unless the if/else chain would be unwieldy otherwise (you couldn't see the whole function on one screen, for example).
dictionary solution is best IMHO