输入年份和月份,判断该月有多少天。用python代码
时间: 2023-05-14 15:06:25 浏览: 103
以下是Python代码实现:
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month in [1, 3, 5, 7, 8, 10, 12]:
print("{}年{}月有31天".format(year, month))
elif month in [4, 6, 9, 11]:
print("{}年{}月有30天".format(year, month))
elif month == 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("{}年{}月有29天".format(year, month))
else:
print("{}年{}月有28天".format(year, month))
else:
print("输入的月份不合法")
```
输入年份和月份后,程序会根据输入的年份和月份判断该月有多少天,并输出结果。
相关问题
python输入年份和月份判断输入的月份有多少天简单代码是什么
以下是判断月份天数的 Python 代码:
```python
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
elif month in [4, 6, 9, 11]:
days = 30
elif month == 2:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days = 29
else:
days = 28
else:
print("输入的月份有误!")
if days:
print("{}年{}月有{}天。".format(year, month, days))
```
代码的实现思路是:先通过 `input` 函数获取用户输入的年份和月份,然后根据不同月份的天数规律,判断该月份有多少天。其中,二月的天数还要根据闰年与否进行特殊判断。最后,使用字符串格式化输出结果(如果用户输入的月份有误则不输出)。
python输入年份和月份判断输入的月份有多少天怎么编写简单代码
可以使用Python自带的calendar库来判断每个月的天数。以下是一个简单的代码示例:
```python
import calendar
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
days = calendar.monthrange(year, month)[1]
print("{}年{}月有{}天".format(year, month, days))
```
代码中,`calendar.monthrange(year, month)[1]`可以获取指定年份和月份的天数。`[1]`表示返回的元组中,第二个元素即为天数。