(1)创建一个列表,依次存放每个月对应的天数。假设2月份的天数固定为28天。 (2)根据用户输入的月份查询该月对应的天数并输出。 你能否将程序设计
时间: 2024-05-13 09:21:04 浏览: 19
成函数形式,输入月份,输出该月对应的天数?
(1) 列表存放每个月对应的天数:
```
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
```
(2) 根据用户输入的月份查询该月对应的天数并输出:
```
month = int(input("请输入月份:"))
print("{}月份有{}天".format(month, days[month-1]))
```
以上是直接输出结果的代码,如果要将其设计成函数形式,可以这样写:
```
def get_days_of_month(month):
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return days[month-1]
month = int(input("请输入月份:"))
print("{}月份有{}天".format(month, get_days_of_month(month)))
```
这样就将查询月份对应天数的功能封装成了一个函数。
相关问题
创建一个列表,依次存放每个月对应的天数。假设2月份的天数固定为28天。根据用户输入的月份查询该月的天数并输出。
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 创建列表存放每个月的天数
month = int(input("请输入月份:")) # 获取用户输入的月份
days = month_days[month - 1] # 查询该月份对应的天数(注意列表下标从0开始)
print("{}月份的天数是{}天。".format(month, days)) # 输出查询结果
Python中创建一个列表,依次存放每个月对应的天数。假设2月份的天数固定为28天。根据用户输入的月份查询该月的天数并输出。
```python
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 存放每个月对应的天数
month = int(input("请输入月份(1-12):")) # 获取用户输入的月份
if month < 1 or month > 12:
print("输入有误!")
else:
print("{}月有{}天。".format(month, days[month-1])) # 输出该月的天数
```
相关推荐
![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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)