首页 › Python 实例 › 判断闰年

Python 判断闰年

数学实例 009

题目

闰年规则:能被 4 整除但不能被 100 整除,或者能被 400 整除。编写函数判断年份是否为闰年,并与标准库结果对比。

参考代码

import calendar

def is_leap(year):
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

for y in [1900, 2000, 2024, 2025, 2100]:
    print(y, "闰年" if is_leap(y) else "平年", "| calendar 结果:", calendar.isleap(y))
执行以上代码输出结果为:
1900 平年 | calendar 结果: False
2000 闰年 | calendar 结果: True
2024 闰年 | calendar 结果: True
2025 平年 | calendar 结果: False
2100 平年 | calendar 结果: False

代码解析

1900 年能被 100 整除但不能被 400 整除,所以是平年;2000 年能被 400 整除,是闰年。标准库 calendar.isleap() 实现了同样的逻辑。