定义一个返回指定年月的天数的函数
时间: 2024-04-30 19:21:01 浏览: 6
可以使用 Python 内置的 `monthrange` 函数实现:
```python
import calendar
def days_in_month(year, month):
return calendar.monthrange(year, month)[1]
```
`monthrange(year, month)` 函数返回一个元组 (weekday of first day of the month, number of days in month),我们只需要取第二个元素即可。例如,调用 `days_in_month(2021, 8)` 将返回 31,因为 2021 年 8 月有 31 天。
相关问题
Python定义一个返回指定年月的天数的函数ndays,并编写测试代码
可以使用Python内置的calendar模块来实现这个功能。
以下是实现代码和测试代码:
```python
import calendar
def ndays(year, month):
return calendar.monthrange(year, month)[1]
# 测试代码
print(ndays(2021, 2)) # 28
print(ndays(2021, 4)) # 30
print(ndays(2022, 2)) # 28
print(ndays(2022, 4)) # 30
print(ndays(2021, 13)) # 报错:ValueError: month must be in 1..12
```
上面的代码中,`calendar.monthrange(year, month)` 返回一个元组 `(weekday of first day of the month, number of days in month)`,我们只需要取第二个值即可得到指定年月的天数。然后,我们定义了一个 `ndays` 函数,接受两个参数:年份和月份,返回该月的天数。最后,我们编写了一些测试代码,确保函数能够正确地工作。
定义函数接收年份和月份,返回对应月份有多少天
以下是一个Python的实现:
```python
def days_in_month(year, month):
"""
返回对应年份和月份的天数
"""
if month == 2:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
return 29
else:
return 28
elif month in [4, 6, 9, 11]:
return 30
else:
return 31
```
这个函数首先判断月份是否为2月,如果是,则根据闰年的定义返回29或28。如果不是2月,则根据每月的天数返回30或31。