Python 闰年检查器

使用 Python 中的标准整除性检查确定一年是否为闰年。

在编辑器中尝试

概述

闰年包含 366 天,而不是 365 天,二月又增加了一天。它的发生是为了使日历年与天文年保持同步。

该规则规定,如果年份能被 4 整除,则该年份为闰年,但世纪年(以 00 结尾的年份)除外,它也必须能被 400 整除。

此计算在 Python 中使用组合逻辑运算符(“and”、“or”)和模运算符来实现。

代码和执行输出

基于整除性的算法来验证多个测试年份,包括世纪年。

def is_leap_year(year):
    # A year is leap if it is divisible by 4
    # and (not divisible by 100 or divisible by 400)
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

years = [2000, 2004, 1900, 2023, 2024]
for y in years:
    status = "Leap Year" if is_leap_year(y) else "Not a Leap Year"
    print(f"Year {y}: {status}")
端子输出
Year 2000: Leap Year
Year 2004: Leap Year
Year 1900: Not a Leap Year
Year 2023: Not a Leap Year
Year 2024: Leap Year

逐步实施

  • 计划、日历和日期时间模块验证
  • 准确确定年龄或日期差异
  • 财务及利息计算公式

常见问题解答

为什么 1900 年不是闰年?

尽管 1900 年可以被 4 整除,但它以 00(世纪年)结束,因此必须能被 400 整除才是闰年。由于 1900 / 400 不是整数,因此不是闰年。

相关主题