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

将ERL转换为Python选择语句以实现闰年判断功能

闰年判断:ERL转Python实现

与原ERL逻辑一致的Python实现

下面的代码严格对应你提供的ERL逻辑,仅调整为Python语法规范:

year = int(input("What year would you like to assess? "))
leap_year = False  # 初始化标记位,后续根据条件更新

# 按闰年规则分步更新标记
if year % 4 == 0:
    leap_year = True
if year % 100 == 0:
    leap_year = False
if year % 400 == 0:
    leap_year = True

# 根据标记输出结果
print("This is a leap year" if leap_year else "This is not a leap year")

说明:

  • Python中用%替代ERL的mod运算符实现取模
  • 用缩进替代ERL的then/endif控制代码块
  • 变量名改为符合PEP8规范的下划线命名风格

更简洁的Pythonic实现

可以将所有判断条件整合为一个逻辑表达式,避免多次修改标记位,代码更高效简洁:

year = int(input("What year would you like to assess? "))

# 直接通过逻辑表达式判断闰年:能被4整除但不能被100整除,或能被400整除
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

print("This is a leap year" if is_leap else "This is not a leap year")

两种实现均遵循闰年判断规则:通常能被4整除的年份为闰年,但能被100整除的年份除外,除非该年份同时能被400整除(如1900年不是闰年,2000年是闰年)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:20:35