python - 几个月写几天的程序

标签 python if-statement

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

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

最佳答案

更好的主意:

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

monthrange(year,month): Returns weekday of first day of the month and number of days in month, for the specified year and 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)

关于python - 几个月写几天的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53196554/

相关文章:

python - 如何检查文本文件是否存在并且在python中不为空

python - 如何在 sudo 上运行 Anaconda Python

ms-access - 需要有关此 IIF 声明的帮助

java - 在java中比较单词中的单词

javascript - 在 JavaScript 中赋值之前如何检查变量是否已定义?

python - 如何过滤字典以仅包含给定列表中的键?

python - 如何轻松地同时遍历行和列?

python - Dropbox python api 列出文件列表

r - 根据条件向值添加字符/字母

c - C语言中的if(变量)是什么意思?