Python itself does not provide a switch syntax, and in order to solve problems like switch branch requirements, we can use dictionaries instead of implementations.
Solution Ideas:
- Handle the default in a switch statement using the fault tolerance of the Get method of the dictionary value
- Set the Vlaue of the dictionary to the corresponding method name instead of the code block in the switch statement
- Set the same value for different keys to simulate a switch that penetrates
DefTaskforsunday(): Print ("Rest Today")DefTaskforrest(): Print ("Rest Today")DefTaskforchinese(): Print ("Today's Chinese Class")def taskformath (): print ( "Today's math Class") def taskforenglish (): print ( "English class Today") Span class= "hljs-function" >def taskfordefault (): print (" input error .... ") Switchdic = {" Sunday ": Taskforrest, " Monday ": Taskforchinese, "Tuesday": Taskformath, "Wednesday": Taskforenglish, "Tursday": Taskforenglish, "Friday": Taskforenglish, " Saturday ": taskforrest}
1. Test values
After getting the method of the dictionary key corresponding to the get, the parentheses are added so that the resulting method will be executed.
"Monday"switchDic.get(day1,taskForDefault)() #打印:今天上语文课
2. Test penetration
##Wednesday,Tursday,Friday三个的效果相同day2 = "Friday"switchDic.get(day2,taskForDefault)() #打印:今天上英语课
3. Test Deault Effect
#字典的get方法第二个参数是默认值,即通过key值不能找到value时,返回默认值#这里使用了自定义函数的函数名:taskForDefault,用于实现switch的defalut功能day3 = "天气不错哦"switchDic.get(day3,taskForDefault)() #打印:输入错误啦。。。。
Python uses dict to mimic switch statement functionality