Python does not have a switch-case statement. The official documentation states that it can be replaced by if-elseif-elseif.
#Also use other solutions, the simpler one is to use a dictionary to achieve the same function. Write a dictionary, and the value corresponding to each key is a method.
For example, switch = {"valueA":functionA,"valueB":functionB,"valueC":functionC}
When calling, it can be like this
try: switch["value"]() #执行相应的方法。 except KeyError as e: pass 或 functionX #执行default部分
The simple code is as follows:
switch = { "a":lambda x:x*2, "b":lambda x:x*3, "c":lambda x:x**x } try: swtich["c"](6) except KeyError as e: pass
You can also write a swtich class yourself to implement the function
The above is the detailed content of Does python have a switch statement?. For more information, please follow other related articles on the PHP Chinese website!