发布时间:2019-08-14 12:47:59编辑:auto阅读(1508)
Python本身并不提供Switch的语法功能,为了能够解决类似switch分支需求的问题,我们可以使用字典代替实现。
解决思路:
def taskForSunday():
print("今天休息")
def taskForRest():
print("今天休息")
def taskForChinese():
print("今天上语文课")
def taskForMath():
print("今天上数学课")
def taskForEnglish():
print("今天上英语课")
def taskForDefault():
print("输入错误啦。。。。")
switchDic = {"Sunday":taskForRest,
"Monday":taskForChinese,
"Tuesday":taskForMath,
"Wednesday":taskForEnglish,
"Tursday":taskForEnglish,
"Friday":taskForEnglish,
"Saturday":taskForRest
}
通过get获取字典key对应的方法后,又添加了个括号,这样会执行得到的方法
day1 = "Monday"
switchDic.get(day1,taskForDefault)() #打印:今天上语文课
##Wednesday,Tursday,Friday三个的效果相同
day2 = "Friday"
switchDic.get(day2,taskForDefault)() #打印:今天上英语课
#字典的get方法第二个参数是默认值,即通过key值不能找到value时,返回默认值
#这里使用了自定义函数的函数名:taskForDefault,用于实现switch的defalut功能
day3 = "天气不错哦"
switchDic.get(day3,taskForDefault)() #打印:输入错误啦。。。。
上一篇: Python中的默认参数详解
下一篇: python查看进程使用内存信息 psu
48876
47944
38725
35866
30292
27048
26077
20911
20718
19077
522°
615°
618°
623°
599°
582°
652°
721°
844°
955°