Learning the Python language, it took a long time to find that Python does not have switch-case statements, view the official document that can be used if-elseif-elseif .... Replace.
Truth be told, none of this is a problem. is not a condition to judge it. -....... with If-elseif Certainly no problem, but also with other solutions, relatively simple is to use
Dictionary to achieve the same function. Write a dictionary, each key corresponds to a value is a method. such as switch = {"Valuea": Functiona, "Valueb": functionb, "VALUEC": Functionc}
Call can be like this
Try
switch["value"] () #执行相应的方法.
Except Keyerror as E:
Pass or Functionx #执行default部分
The simple code is as follows:
1 switch = {
2 "a": Lambda x:x*2,
3 "B": Lambda x:x*3,
4 "C": Lambda x:x**x
5}
6
7 Try:
8 swtich["C"] (6)
9 except Keyerror as E:
It's no problem if you don't bother writing a swtich class to achieve it. But is that really necessary?