python判断闰年

Python016

python判断闰年,第1张

用Python判断是否是闰年的三种方法:

本教程操作环境:windows7系统、python3.9版,DELL G3电脑。

1、以下实例可以判断用户输入的年份是否为闰年

2、也可以使用内嵌if语句来实现:

执行以上代码输出结果为:

3、其实Python的calendar库中已经封装好了一个方法isleap()来实现这个判断是否为闰年:

根据用户输入判断:

下面是一个 Python 程序,可以用来判断一个年份是否是闰年:

# 定义函数 is_leap_year,用来判断某个年份是否是闰年

def is_leap_year(year):

# 闰年的条件是:

# 1. 能被 4 整除,但不能被 100 整除

# 2. 能被 400 整除

return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

# 测试函数

assert is_leap_year(2000) == True   # 2000 是闰年

assert is_leap_year(2004) == True   # 2004 是闰年

assert is_leap_year(1900) == False  # 1900 不是闰年

assert is_leap_year(2003) == False  # 2003 不是闰年

上面的代码定义了一个函数 is_leap_year,该函数接收一个年份作为参数,并返回一个布尔值,表示该年份是否是闰年。

闰年的定义是:

能被 4 整除,但不能被 100 整除

能被 400 整除

这两个条件可以用一个条件语句表示出来:

(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

如果满足上述条件之一,则返回 True,否则返回 False。

在上面的程序中,还使用了 Python 的断言语句 assert 来测试函数的正确性。在断言语句中,我们对函数的输出结果进行比较,如果与预期不符,则会触发 AssertionError 错误。这是一种非常方便的测试方法。