我们都知道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语句