用于检查闰年的 Python 程序

要理解这个例子,你应该具备以下 Python 编程 主题的知识


闰年能被4整除,但不能被100整除(世纪年除外)。世纪年只有在能被400整除时才是闰年。例如,

2017 is not a leap year
1900 is a not leap year
2012 is a leap year
2000 is a leap year

源代码

# Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user
# year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
    print("{0} is a leap year".format(year))

# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
    print("{0} is a leap year".format(year))

# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
    print("{0} is not a leap year".format(year))

输出

2000 is a leap year

您可以在源代码中更改 year 的值,然后再次运行它来测试这个程序。


另请阅读

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算两个给定年份之间的闰年数量。

  • 提示:如果一个年份能被4整除,但不能被100整除,除非它也能被400整除,那么它就被认为是闰年。
  • 例如,对于输入 20002020,输出应该是 6
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战