Python Forum
Help: write 'case' with Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help: write 'case' with Python (/thread-32203.html)



Help: write 'case' with Python - ICanIBB - Jan-27-2021

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?


RE: Help: write 'case' with Python - nilamo - Jan-27-2021

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).


RE: Help: write 'case' with Python - Larz60+ - Jan-27-2021

dictionary solution is best IMHO