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

为何我编写的Python闰年判断函数未输出预期结果?

为什么输入2100时,闰年判断函数未返回预期的False?

问题背景

需求是实现is_leap函数,输入年份后返回布尔值:闰年返回True,非闰年返回False,判断规则遵循格里高利历:

  • 年份能被4整除则为闰年,除非:
    • 年份能被100整除则不是闰年,除非:
      • 年份同时能被400整除,那么它是闰年。

现有代码如下:

def is_leap(year):
    leap= False

    if (year % 400 == 0) and (year % 100 == 0):
        leap = True
    elif (year % 4 ==0) and (year % 100 != 0):
        leap=True
    else:
        pass

year = int(input())
print(is_leap(year))

当输入2100时,预期输出为False,但实际运行结果不符合预期,问题出在哪里?

问题根源

核心问题是**is_leap函数缺少返回语句**。Python中,如果函数没有显式的return语句执行,会默认返回None,而不是你设置的leap变量值。

针对2100的执行流程:

  1. 2100无法被400整除,第一个if条件不成立;
  2. 2100能被4整除,但同时也能被100整除,因此elif条件也不成立;
  3. 进入else分支执行pass,leap变量保持初始值False;
  4. 函数没有返回leap,最终返回None,所以打印结果是None而非预期的False。

修复方案

在函数末尾添加return leap语句,让函数返回正确的布尔值:

def is_leap(year):
    leap= False

    if (year % 400 == 0) and (year % 100 == 0):
        leap = True
    elif (year % 4 ==0) and (year % 100 != 0):
        leap=True
    else:
        pass
    
    return leap  # 添加返回语句

year = int(input())
print(is_leap(year))

另外可以简化第一个判断条件——能被400整除的年份必然能被100整除,所以不需要额外判断year % 100 == 0,简化后逻辑完全一致:

def is_leap(year):
    leap= False

    if year % 400 == 0:
        leap = True
    elif year % 4 == 0 and year % 100 != 0:
        leap = True
    
    return leap

内容的提问来源于stack exchange,提问作者Kami Sama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:31:08