为何我编写的Python闰年判断函数未输出预期结果?
为什么输入2100时,闰年判断函数未返回预期的False?
问题背景
需求是实现is_leap函数,输入年份后返回布尔值:闰年返回True,非闰年返回False,判断规则遵循格里高利历:
- 年份能被4整除则为闰年,除非:
- 年份能被100整除则不是闰年,除非:
- 年份同时能被400整除,那么它是闰年。
- 年份能被100整除则不是闰年,除非:
现有代码如下:
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的执行流程:
- 2100无法被400整除,第一个
if条件不成立; - 2100能被4整除,但同时也能被100整除,因此
elif条件也不成立; - 进入
else分支执行pass,leap变量保持初始值False; - 函数没有返回
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
相关产品推荐
相关产品推荐

