python获取用户输入月份,输出该月有多少天(考虑闰年)。
时间: 2023-10-26 07:12:14 浏览: 69
以下是Python代码,用于获取用户输入月份并输出该月有多少天(考虑闰年):
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 判断是否为闰年
is_leap_year = False
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
is_leap_year = True
# 判断每个月的天数
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
else:
if is_leap_year:
days = 29
else:
days = 28
print("{0}年{1}月有{2}天".format(year, month, days))
```
在代码中,首先通过 `input` 函数获取用户输入的年份和月份,并将其转换为整数。然后,判断该年份是否为闰年,如果是,则将 `is_leap_year` 标记设置为 `True`。接着,根据月份判断该月的天数,如果是大月份(1、3、5、7、8、10、12),则天数为 31 天;如果是小月份(4、6、9、11),则天数为 30 天;如果是二月份,则根据是否闰年来判断天数。最后,使用 `print` 函数输出结果。
注意:在Python 2.x版本中,应该使用 `raw_input` 函数代替 `input` 函数。