让用户输入一个月份 返回这个月的天数
时间: 2023-05-24 21:02:54 浏览: 64
A:请使用以下代码实现:
```python
month = int(input("请输入一个月份(1-12):"))
if month in [1, 3, 5, 7, 8, 10, 12]:
print("这个月有31天")
elif month in [4, 6, 9, 11]:
print("这个月有30天")
elif month == 2:
year = int(input("请输入一个年份:"))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("这个月有29天")
else:
print("这个月有28天")
else:
print("输入有误,请重新输入")
```
代码的逻辑是先判断月份是否在1、3、5、7、8、10、12中,如果是,则这个月有31天;如果不是,则判断月份是否在4、6、9、11中,如果是,则这个月有30天;如果也不是,则判断月份是否为2,如果是,则需要让用户输入一个年份,再根据闰年的规则判断这个月有28天还是29天。如果月份既不在1到12中,也不是2,则输出输入有误的提示。
相关问题
让用户输入一个月份 返回这个月的天数 用break
来跳出循环并输出结果。
A:
```python
while True:
month = input("请输入月份:")
if month.isdigit() and 1 <= int(month) <= 12:
break # 输入合法,跳出循环
print("输入无效,请重新输入!")
month = int(month)
if month == 2:
print("这个月份有28天")
else:
if month in [1, 3, 5, 7, 8, 10, 12]:
print("这个月份有31天")
else:
print("这个月份有30天")
```
这里使用了`while True`循环,不断要求用户输入一个月份。如果输入无效(非数字或数字不在1-12之间),则打印提示信息并重新循环。如果输入合法,那么通过`break`跳出循环。
接下来对月份进行判断,并输出有多少天。对于2月份,直接输出28天;对于其他月份,判断它是否为31天的月份,如果是就输出31天,否则输出30天。
给定年份和月份判断这个月的天数
以下是给定年份和月份判断这个月的天数的Python代码:
```python
def MonthDays(year, month):
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
elif month == 2:
if year % 400 == 0:
return 29
elif year % 4 == 0 and year % 100 != 0:
return 29
else:
return 28
else:
return None
```
该函数接受年份和月份作为输入,返回该月的天数。其中,对于2月份的天数判断,根据闰年的定义进行判断。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)