我需要编写一个返回假日的函数,给定数字和月份(7 4是7月4日)。
要返回的假期是:
1 1 "New Year's Day"
2 14 "Valentine's Day"
4 1 "April Fool's Day"
4 22 "Earth Day"
5 1 "May Day"
6 14 "Flag Day"
7 4 "Independence Day"
7 14 "Bastille Day"
10 31 "Halloween"
12 25 "Christmas"
如果一天不是假期,则应返回“不是假期”。
这是我尝试过的方法,它无法按预期工作。如果我输入4 1,我的代码就是元旦。
def holiday(month,day):
if month and day in (1, 1):
return "New Year's Day"
if month and day in (2, 14):
return "Valentine's Day"
if month and day in (4, 1):
return "April Fool's Day"
if month and day in (4,22):
return "Earth Day"
if month and day in (5, 1):
return "May Day"
if month and day in (6, 14):
return "Flag Day"
if month and day in (7, 4):
return "Independence Day"
if month and day in (7, 14):
return "Bastille Day"
if month and day in (10 ,31):
return "Halloween"
if month and day in (12, 25):
return "Christmas"
答案 0 :(得分:4)
想到的最简单的解决方案是通过dict访问值,因此您不必编写一堆if
语句..如果不存在假期,只需 ,然后编写您自己的消息。
例如:
def holiday():
return {
1: {
1: "New Year"
},
2: {
14: "Valentines Day"
}
}
try:
print(holiday()[2][14])
except KeyError:
print("No holiday :(")
请记住,您不需要为此的函数,只需简单的字典就可以了,但是您说我需要编写一个函数,这样就可以了:)