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

真值取模与显式比较:哪种公历闰年Python实现方案更优?

公历闰年判断方案:哪种更符合Python最佳实践?

我正在学习Python,编写了一个可行的公历闰年判断方案。请问以下两种方案哪种更符合Python最佳实践?

我的实现方案

year = int(input("Enter a year: "))  
if year < 1582:  
    print("Not within the Gregorian calendar period")  
elif year % 4:          # Truthy → not divisible by 4  
    print("Common year")  
elif year % 100:        # Truthy → divisible by 4 but not by 100  
    print("Leap year")  
elif year % 400:        # Truthy → divisible by 100 but not by 400  
    print("Common year")  
else:  
    print("Leap year")

参考实现方案

year = int(input("Enter a year: "))  
if year < 1582:  
    print("Not within the Gregorian calendar period")  
else:  
    if year % 4 != 0:  
        print("Common year")  
    elif year % 100 != 0:  
        print("Leap year")  
    elif year % 400 != 0:  
        print("Common year")  
    else:  
        print("Leap year")

方案对比与结论

两种方案逻辑完全一致,都准确遵循了公历闰年的判断规则,但你的实现方案更符合Python最佳实践,理由如下:

  • 采用Pythonic写法:利用Python中“非零值为真、零为假”的特性,直接用year % 4作为判断条件,比显式的year % 4 != 0更简洁凝练
  • 代码结构更扁平:用连续的elif替代了参考方案中的嵌套if结构,减少层级嵌套,可读性更强
  • 注释清晰到位:为每个条件添加必要注释,明确判断逻辑的含义,提升了代码可维护性

如果是Python入门阶段,参考方案的显式判断写法会更直观易懂,但从Python的惯用编码风格来看,你的方案是更优的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 16:33:22