编写函数判断闰年Python
时间: 2025-07-04 16:15:09 浏览: 8
### 判断闰年的函数实现
在 Python 中,可以通过定义一个函数来判断某一年是否为闰年。该函数的逻辑基于闰年的定义规则:
1. 如果年份能被 4 整除但不能被 100 整除,则是闰年。
2. 如果年份能被 400 整除,则也是闰年。
以下是一个简洁且高效的实现方式:
```python
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
```
此函数返回布尔值 `True` 或 `False`,表示给定年份是否为闰年。例如,调用 `is_leap_year(2020)` 将返回 `True`,而 `is_leap_year(1900)` 返回 `False`[^2]。
如果希望直接输出结果而不是返回布尔值,可以扩展函数如下:
```python
def check_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print(f"{year} 是闰年")
else:
print(f"{year} 不是闰年")
```
此外,还可以利用 Python 内置模块 `calendar` 提供的 `isleap()` 方法简化判断过程:
```python
import calendar
def check_leap_year_with_calendar(year):
if calendar.isleap(year):
print(f"{year} 是闰年")
else:
print(f"{year} 不是闰年")
```
这种方法通过调用标准库中的功能,确保了准确性并减少了手动编写条件判断的工作量[^3]。
### 使用示例
以下是使用上述函数的一些示例:
```python
print(is_leap_year(2020)) # 输出: True
check_leap_year(2020) # 输出: 2020 是闰年
check_leap_year(1900) # 输出: 1900 不是闰年
check_leap_year_with_calendar(2000) # 输出: 2000 是闰年
```
这些函数可以根据具体需求灵活调整和集成到更大的程序中。
阅读全文
相关推荐


















