用python完成函数,指出指定月份有多少天,不考虑闰年,2月按照28天计算。
时间: 2024-02-20 20:02:16 浏览: 40
可以使用Python内置的`calendar`模块来实现。具体代码如下:
```python
import calendar
def days_in_month(month):
return calendar.monthrange(2021, month)[1]
print(days_in_month(2)) # 输出28
print(days_in_month(4)) # 输出30
print(days_in_month(12)) # 输出31
```
其中`monthrange()`函数返回一个元组`(weekday of first day of the month, number of days in month)`,我们只需要取第二个元素即可得到指定月份的天数。
相关问题
用python完成函数,指出指定月份有多少天,不考虑闰年,2月按照28天计算。,例如,输入7,打印31
可以使用字典存储每个月份对应的天数,然后根据输入的月份返回对应的天数。具体实现如下:
```python
def days_in_month(month):
days = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
return days.get(month, 0)
# 测试
print(days_in_month(7)) # 输出 31
```
在函数中,我们使用一个字典 `days` 存储每个月份对应的天数,然后使用 `get` 方法获取输入的月份对应的天数,如果输入的月份不在字典中,则返回默认值 0。最后在测试时,我们输入 7,函数返回 31,符合预期结果。
用python根据月份判断该月有多少天 不考虑闰年
可以使用 if-elif 语句根据月份判断该月有多少天,示例代码如下:
```python
month = int(input("请输入月份:"))
if month == 2:
days = 28
elif month in [4, 6, 9, 11]:
days = 30
else:
days = 31
print("该月有 %d 天" % days)
```
在代码中,首先使用 `input` 函数获取用户输入的月份,然后使用 `if-elif` 语句判断该月份有多少天,最后通过 `print` 函数将结果输出。注意,由于 `input` 函数返回的是字符串类型,因此需要使用 `int` 函数将其转换为整数类型。
相关推荐
![](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)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)