python如何使用字典实现switch

1、构建字典。前面key的数字代表用户输入的功能序号。value代表相应的功能函数。

这些函数是根据业务需求实现的普通函数。

2、使用循环。捕捉用户输入,然后执行。

实例

#-*-coding:UTF-8-*-
"""
@author:AmoXiang
@file:28.使用字典实现switch结构.py
@time:2021/02/01
"""


defget_monday():#定义函数
return"星期一"#返回星期一


defget_tuesday():
return"星期二"#返回星期二


defget_wednesday():
return"星期三"#返回星期三


defget_thursday():
return"星期四"#返回星期四


defget_friday():
return"星期五"#返回星期五


defget_saturday():
return"星期六"#返回星期六


defget_sunday():
return"星期日"#返回星期日


defget_default():
return"不知道星期几"#模拟swtich语句中的default语句功能


switcher={#通过字典映射来实现switch/case功能
1:get_monday,#通过键不同,调用不同的函数
2:get_tuesday,
3:get_wednesday,
4:get_thursday,
5:get_friday,
6:get_saturday,
7:get_sunday
}
foriinrange(2):#测试2次
day=input("今天是一周第几天?:").strip()#手动输入一个天数
ifday.isdigit():#判断是否是数字
day=int(day)#转换为int型
else:
day=0#设置day值为0
day_name=switcher.get(day,get_default)()#当day不在字典映射中时,调用get_default()
print(f"今天{day_name}")

以上就是python使用字典实现switch的方法,希望对大家有所帮助。更多Python学习指路:Python基础教程

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。