输入年份和月份,输出该年该月的天数
时间: 2023-11-28 22:52:26 浏览: 59
以下是Python代码实现:
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
# 判断闰年,闰年2月有29天,平年2月有28天
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
days_of_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
else:
days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
print("{}年{}月的天数为:{}".format(year, month, days_of_month[month - 1]))
```
代码首先通过`input`函数获取用户输入的年份和月份。然后判断该年是否为闰年,如果是闰年则2月有29天,否则2月有28天。最后输出该年该月的天数。需要注意的是,由于Python中列表的下标是从0开始的,因此获取该月天数时需要将月份减1。
相关问题
输入年份和月份,输出该月天数
这是一个常见的编程问题,可以使用以下代码来解决:
```python
import calendar
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
days = calendar.monthrange(year, month)[1]
print(f"{year}年{month}月有{days}天。")
```
这个程序使用了 Python 的 calendar 模块,其中的 monthrange 函数可以返回指定年份和月份的第一天是星期几以及该月的天数。我们只需要取出第二个返回值即可得到该月的天数。
输入年份和月份,输出该月的天数
以下是Python的代码实现:
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month == 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
days = 29
else:
days = 28
elif month in [4, 6, 9, 11]:
days = 30
else:
days = 31
print(f"{year}年{month}月共有{days}天。")
```
代码逻辑如下:
1. 首先通过input函数获取用户输入的年份和月份,使用int函数将输入的字符串转换为整数类型。
2. 判断月份是否为2月,如果是则需要特殊处理。如果该年份为闰年,2月有29天;否则2月有28天。
3. 如果月份为4、6、9、11中的任意一个,该月有30天。
4. 如果月份既不是2月,也不是4、6、9、11中的任意一个,则该月有31天。
5. 将结果输出。