Python成长记十六(python中的
短信预约 -IT技能 免费直播动态提醒
我们都知道python中没有switch case语句这种写法,那么我们怎样使用python实现同样的功能呢?
其他语言的switch case语句语法如下:
switch(n)
{
case 1:
执行代码块 1
break;
case 2:
执行代码块 2
break;
default:
n 与 case 1 和 case 2 不同时执行的代码
}
比如在JavaScript里可以这么写:
var day=new Date().getDay();
switch (day)
{
case 0:
x="Today it's Sunday";
break;
case 1:
x="Today it's Monday";
break;
case 2:
x="Today it's Tuesday";
break;
case 3:
x="Today it's Wednesday";
break;
case 4:
x="Today it's Thursday";
break;
case 5:
x="Today it's Friday";
break;
case 6:
x="Today it's Saturday";
break;
default:
x="Looking forward to the Weekend";
}
那么在python中我们怎么样实现呢?
解决方案:用字典映射代表switch case语句
实现以上语句如下:
import datetime
day = datetime.datetime.now().weekday()
def get_sunday():
return "Today it's Sunday"
def get_monday():
return "Today it's Monday"
def get_tuesday():
return "Today it's Tuesday"
def get_wednesday():
return "Today it's Wednesday"
def get_thursday():
return "Today it's Thursday"
def get_friday():
return "Today it's Friday"
def get_saturday():
return "Today it's Saturday"
def get_default():
return "Looking forward to the Weekend"
switcher = {
0:get_sunday,
1:get_monday,
2:get_tuesday,
3:get_wednesday,
4:get_thursday,
5:get_friday,
6:get_default
}
dayName = switcher.get(day,get_default)()
print(dayName)
总结:我们可以使用字典的方式实现switch语句
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341