Python Forum
Help: write 'case' with Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help: write 'case' with Python
#1
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?
Reply
#2
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).
ICanIBB likes this post
Reply
#3
dictionary solution is best IMHO
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What colon (:) in Python mean in this case? Yapwc 4 2,052 Dec-28-2022, 04:04 PM
Last Post: snippsat
  Switch case or match case? Frankduc 9 4,386 Jan-20-2022, 01:56 PM
Last Post: Frankduc
  Logstash - sending Logstash messages to another host in case of Failover in python Suriya 0 1,641 Jul-27-2021, 02:02 PM
Last Post: Suriya
  How to use switch/case in python? newbieguy 9 3,955 Nov-08-2019, 11:35 AM
Last Post: newbieguy
  How to write switch case statement in Python pyhelp 9 9,041 Nov-11-2018, 08:53 PM
Last Post: woooee
  Is there a better way to write this case scenario? anakaine 15 8,458 Sep-26-2017, 04:33 PM
Last Post: buran
  Is there a something like "case" in Python 3.6? Raptor88 18 20,510 Feb-27-2017, 02:44 AM
Last Post: Raptor88

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020