首页 > 编程知识 正文

Python 程序:检查年份是否是闰年

时间:2023-11-25 09:12:55 阅读:309043 作者:TPWG

为了更好地理解这个例子,我们总是建议您学习下面列出的 Python 编程的基本主题:

  • Python 语法
  • Python 数据类型
  • Python 决策语句

什么是闰年?

闰年是有 366 天的一年。实际上,我们理解为检查 2 月有 28 天。现在我们必须知道如何在 python 程序中检查这一点。

如何在 python 程序中检查闰年?

闰年是可以被 4 整除的一年。该解决方案适用于除百年[00 年结束的年份]以外的所有年份。我们必须检查它是否能被 400 整除;如果它能被 400 完全整除,那将是一个闰年。

在 python 程序中,因此我们必须使用if条件和elif语句来检查它是否可以被 4 或 400 整除,以确认该年是否是闰年。Python 语言使用 Mod 运算符进行可分性检查。

算法

步骤 1: 从用户处接受该年的值。(python 编程语言只接受使用输入函数的字符串,因此我们必须在使用 int 运算符保存值之前将该字符串转换为整数)。

STEP 2: 使用 if 条件和 mod 运算符检查给定年份是否可被 4 整除,是否不可被 100 整除。然后将给定年份打印为闰年。

STEP 3: 使用elif 语句检查年份是否完全被 100 整除,然后打印给定年份不是闰年。

STEP 4: 使用elif语句检查给定的年份是否可以被 400 整除,打印的年份是闰年。

STEP 5: 使用 python 语言的else语句打印给定年份不是闰年。

Python 源代码

year = int(input("Please enter the year to check: "))  # accept the year from user

# Leap Year Check

if (
    year % 4 == 0 and year % 100 != 0
):  # checking the year is divisible by 4 and not divisible by 100
    print(year, "it is a leap year")  # print its a leap year
elif year % 100 == 0:

    # check the year divisible by 100

    print(year, "Entered value is not a leap year")
elif year % 400 == 0:

    # checking the year is divisible by 400

    print(year, "it is a leap year")
else:
    print(year, "Entered value is not a leap year") 

输出

Please enter the year to check:  2004

2004 it is a leap year

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。