首页 > 解决方案 > 几个月内写几天的程序

问题描述

因此,我正在尝试编写一个代码,无论月份是多少,它都会返回我这个月的天数。这是我目前编写的代码。我得到了一些正确的月份,但其余的不是。有人可以指出我在编码方面做错了什么吗?

def get_days_in_month (month):
    if (month == 2):
        return 28
    elif (month == 4 + 6 + 9 + 11):
        return 30
    elif (month == 1 + 3 + 5 + 7 + 8 + 10 +12):
        return 31
    else:
        return 31

标签: pythonif-statement

解决方案


更好的主意:

使用 python 的内置计算器。使用monthrange并传入(int)的年月

monthrange(year,month):返回指定年份和月份的月份第一天的工作日和月份的天数

from calendar import monthrange

def get_days_in_month (year,month):
    month_data= monthrange(year, month)
    # If you only want DAYS, use month_data[1] 
get_days_in_month(2018,1)

推荐阅读