You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python判断闰年?求正确的Python闰年判断代码

Python 闰年检测的正确实现方法

闰年判定规则

闰年需满足以下两个条件之一:

  • 能被4整除,但不能被100整除;
  • 能被400整除。

正确代码实现

def is_leap_year(year):
    # 输入验证:确保年份为有效正整数
    if not isinstance(year, int) or year <= 0:
        raise ValueError("年份必须是正整数")
    
    # 核心闰年判断逻辑
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    else:
        return False

代码说明

  1. 输入验证:可选但推荐的步骤,过滤无效的非正整数输入,避免逻辑判断出错;
  2. 核心判断:严格遵循国际通用的闰年判定标准,两个条件满足其一即可判定为闰年。

测试示例

# 验证闰年
print(is_leap_year(2000))  # 输出: True(能被400整除)
print(is_leap_year(2024))  # 输出: True(能被4整除但不能被100整除)

# 验证非闰年
print(is_leap_year(1900))  # 输出: False(能被100整除但不能被400整除)
print(is_leap_year(2023))  # 输出: False(无法被4整除)

内容的提问来源于stack exchange,提问作者Chetan perajapat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 14:45:27