Python代码 在线执行

Python 程序:检查闰年

/examples/leap-year

在该程序中,您将学习检查年份是否为闰年。 我们将使用嵌套if...else解决此问题。

要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:


除世纪年份(以 00 结尾的年份)外,闰年可精确地除以 4。 只有将世纪完全除以 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: "))

if (year % 4) == 0:
   if (year % 100) == 0:
       if (year % 400) == 0:
           print("{0} is a leap year".format(year))
       else:
           print("{0} is not a leap year".format(year))
   else:
       print("{0} is a leap year".format(year))
else:
   print("{0} is not a leap year".format(year)) 

输出

2000 is a leap year

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