首页 > 解决方案 > 在给定月份和日期的情况下确定假期

问题描述

我需要编写一个函数来返回假期,以数字形式给出月份和日期(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"

标签: python

解决方案


想到的最简单的解决方案是通过 dict 访问值,因此您不必编写一堆if语句.. 如果假期不存在,只需捕获异常并编写您自己的消息。

例如:

def holiday():
     return {
        1: {
            1: "New Year"
        },
        2: {
            14: "Valentines Day"
        }
    }

try:
    print(holiday()[2][14])
except KeyError:
    print("No holiday :(")

请记住,您不需要为此使用函数,只需一个简单的 dict 就可以了,但是您说我需要编写一个函数,这样就可以了 :)


推荐阅读