python考虑闰年,输出该月有多少天
时间: 2023-10-26 13:17:25 浏览: 110
键盘输入一个年和一个月,能输出该月总共有多少天
下面是一个示例代码,可以考虑闰年并输出指定月份的天数:
```python
def days_in_month(year, month):
# 判断是否为闰年
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
leap_year = True
else:
leap_year = False
# 判断月份天数
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
else:
if leap_year:
days = 29
else:
days = 28
return days
# 测试
print(days_in_month(2020, 2)) # 29
print(days_in_month(2021, 2)) # 28
print(days_in_month(2021, 4)) # 30
print(days_in_month(2021, 5)) # 31
```
阅读全文