python用if函数输入月份判断天数
时间: 2024-02-28 11:28:03 浏览: 19
好的,可以为您提供代码如下:
```
month = int(input("请输入月份:"))
if month == 2:
print("28或29天")
elif month in [4, 6, 9, 11]:
print("30天")
else:
print("31天")
```
请您自行复制,代码中的if语句判断月份,elif语句判断不同月份的天数,else语句为剩余月份的天数。希望对您有所帮助。
相关问题
python用if函数输入月份判断天数和闰年
好的!这是一个常见的问题,以下是Python代码实现:
```
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month in [1, 3, 5, 7, 8, 10, 12]: # 31天
print("{}年{}月有31天。".format(year, month))
elif month in [4, 6, 9, 11]: # 30天
print("{}年{}月有30天。".format(year, month))
elif month == 2: # 2月,需要判断是否为闰年
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("{}年2月有29天,是闰年。".format(year))
else:
print("{}年2月有28天。".format(year))
else:
print("输入月份有误,请重新输入!")
```
希望能够帮助您。
python输入月份判断天数
可以使用Python中的calendar库来实现。下面是示例代码:
```python
import calendar
while True:
month_str = input("请输入月份(1-12):")
if not month_str.isdigit():
print("输入错误,请输入数字!")
continue
month_int = int(month_str)
if month_int < 1 or month_int > 12:
print("输入错误,请输入1-12的数字!")
continue
else:
break
year_str = input("请输入年份:")
if not year_str.isdigit():
print("输入错误,请输入数字!")
exit()
year_int = int(year_str)
days = calendar.monthrange(year_int, month_int)[1]
print("{}年{}月有{}天".format(year_int, month_int, days))
```
输入月份和年份后,调用calendar.monthrange()函数得到该月份的天数,最后将结果输出。