python笔记之判断月份有多少天

发布于:2025-03-27 ⋅ 阅读:(35) ⋅ 点赞:(0)

1、通过随机数作为目标月份

import random
month = random.randint(1,12)

2、判断对应的年份是闰年还是平年

因为2月这个特殊月份,闰年有29天,而平年是28天,所以需要判断对应的年份属于闰年还是平年,代码如下

# 判断年份是闰年还是平年
def guess_year(year):
    if year % 400 == 0:
        return True
    elif year % 100 != 0 and year % 4 == 0:
        return True
    return False

3、返回对应月份的天数

若是大月,对应31天;小月则是30天;2月根据是闰年还是平年返回29或者28天

3.1、判断当前月是哪种类型

big_month = [1, 3, 5, 7, 8, 10, 12]
big_month_days = 31
big_month_type = 1

small_month = [4, 6, 9, 11]
small_month_days = 30
small_month_type = 2

special_month = [2]
special_month_type = 3

# 判断月份是大月、小月还是平月
def guess_month_type(month):
    match month:
        case month if month in big_month:
            return big_month_type
        case month if month in small_month:
            return small_month_type
        case month if month in special_month:
            return special_month_type
        case _:
            raise Exception("Invalid month")

3.2、根据月份的类型和年份类型,返回目标月份的天数

# 返回一个月的天数
def get_month_days(year, month):
    # 获取月份类型
    month_type = guess_month_type(month)
    match month_type:
        case month_type if month_type == big_month_type:
            return big_month_days
        case month_type if month_type == small_month_type:
            return small_month_days
        case month_type if month_type == special_month_type:
            # 2月判断年份是闰年还是平年
            if guess_year(year):
                return 29
            else:
                return 28
        case _:
            raise Exception("Invalid month type")

4、测试代码

if __name__ == "__main__":
    year = int(input("请输入年份:"))
    month = random.randint(1,12)
    month_days = get_month_days(year, month)
    print(f'{month}月有{month_days}天')