Does Python implement switch/case
at all or are python developers suppose to use a series of if, elif, else
statements instead?
Asked
Active
Viewed 931 times
1

pHorseSpec
- 1,246
- 5
- 19
- 48
1 Answers
6
Python does not implement a switch
. An alternative is using a dict like so:
def func1():
pass
def func2():
pass
switch = {
"do1": func1,
"do2": func2,
}
do_str = "do1"
switch[do_str]()

Bharel
- 23,672
- 5
- 40
- 80
-
1Using dictionary is the elegant way, especially if you have "many" cases (whatever many could mean to you). For few choices, use the simpler if .. elif .. else construct. This is what Python documentation recommends: https://docs.python.org/3/tutorial/controlflow.html – Cyb3rFly3r Apr 12 '16 at 19:38