确定闰年

2024-04-24 16:38:58 发布

您现在位置:Python中文网/ 问答频道 /正文

如果能被4整除,我们知道这是闰年,如果是世纪年,它可以被400整除。我想我需要两个这样的If语句:

def isLeap(n):

if n % 100 == 0 and n % 400 == 0:
    return True
if n % 4 == 0:
    return True
else:
    return False

# Below is a set of tests so you can check if the code is correct.

from test import testEqual

testEqual(isLeap(1944), True)
testEqual(isLeap(2011), False)
testEqual(isLeap(1986), False)
testEqual(isLeap(1956), True)
testEqual(isLeap(1957), False)
testEqual(isLeap(1800), False)
testEqual(isLeap(1900), False)
testEqual(isLeap(1600), True)
testEqual(isLeap(2056), True)

当我尝试上面的代码时,我收到了多年的错误消息

^{pr2}$

基本上,我需要我的代码来说明“如果一年可以被4整除,那么这个测试是正确的,如果它是一个世纪年,它可以被400整除。”但是当我尝试:

if n % 4 and (n % 100 == 0 and n % 400 == 0):
    return True
else: 
    return False

我收到三条错误信息(多年来)

1944 - Test Failed: expected True but got False
1956 - Test Failed: expected True but got False
2056 - Test Failed: expected True but got False

所以看起来我创造了第二个条件(可以被100和400整除)抵消了可以被4整除的年份。在


Tags: andtestfalsetruereturnifiselse
3条回答

试试这个:

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

问题是你希望一年可以被4整除,如果它是一个世纪年,就可以被400整除。在

^{pr2}$

正如评论中提到的,这已经是内置的:calendar.isleap

你可以看到source here它很简单:

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

写出的长格式如下所示(1600年以上):

def isLeapYear(year):
    if year % 4 != 0:
        return False
    elif year % 100 != 0:
        return True
    elif year % 400 != 0:
        return False
    else:
        return True

相关问题 更多 >