python - 在给定月份和日期的情况下确定假期
问题描述
我需要编写一个函数来返回假期,以数字形式给出月份和日期(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"
如果当天不是节假日,则应返回“Not a holiday”。
这是我尝试过的,它不会按预期工作。如果我输入 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"
解决方案
想到的最简单的解决方案是通过 dict 访问值,因此您不必编写一堆if
语句.. 如果假期不存在,只需捕获异常并编写您自己的消息。
例如:
def holiday():
return {
1: {
1: "New Year"
},
2: {
14: "Valentines Day"
}
}
try:
print(holiday()[2][14])
except KeyError:
print("No holiday :(")
请记住,您不需要为此使用函数,只需一个简单的 dict 就可以了,但是您说我需要编写一个函数,这样就可以了 :)
推荐阅读
- css - 选择器超出选择器最大特异性
- sql - SQL (ANSII) 中窗口函数中的 CASE 表达式
- ballerina - 访问结果集而不将其转换为 Json 或 XML ballerina.io
- sql - MSSQL 为每条记录选择前 2 名
- javascript - 赛普拉斯拦截与 url 不匹配
- python - SQLAlchemy Marshmallow 返回空 JSON Flask
- python - 使用 Python 分割 JSON 文件的最简单方法
- javascript - 棘手的“for”循环的输出?
- c# - 如何创建将 JSON 列表对象作为参数并且有多个请求的 ASYNC POST API?如何在 Postman 中测试多请求?
- primeng - Prime ng 日历 UTC