闰年判断的三种实现方法

时间:2025-04-15 18:04:46
# 闰年判断
# 方法一:①能直接被4整除且不能被100整除的是闰年,eg:1900不是闰年;②能直接被400整除的是闰年,eg:2000是闰年
# 以下代码由于能被400整除的年份一定可以被4整除,所有直接放在一个大的判断条件下(year%4是否与0相等)
year = int(input("请输入一个年份:"))
if (year % 4) == 0:
    if (year % 100) != 0:
        print("%s年是闰年" % year)
    else:
        if (year % 400) == 0:
            print("%s年是闰年" % year)
        else:
            print("%s年不是闰年" % year)
else:
    print("%s年不是闰年" % year)

# 方法二:自定义函数的方法

def is_run(year):
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print("该年是闰年")
    else:
        print("该年不是闰年")


year = int(input("请输入年份:"))
is_run(year)


# 方法三:    在开头加上 import calendar,使用其中的内部函数isleap(year)可以直接判断,但是不建议,这样不利于代码逻辑建立
# 注意:调用isleap时要求加上calender,即; 常用的用法还有 , (), ()等
# isleap返回值为True或者False,不能使用==True 要用is True
import calendar
year = int(input("请输入年份:"))
if (year) is True:
    print("该年份为闰年")
else:
    print("该年份不是闰年")