我们知道这是一个闰年,如果它是被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)
当我尝试上面的代码,我得到的错误消息年
1800 - Test Failed: expected False but got True
1900 - Test Failed: expected False but got True
基本上我需要我的代码说,“如果今年四整除的测试结果是真,并且,如果它是一个世纪以来,它的整除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
你应该比较'如果n%4'的东西? –
'n%100 == 0和n%400 == 0'是多余的;如果它可以被400整除,它总会被100整除。想想你的数学有点难。 –
顺便说一句,[已经回答](https://stackoverflow.com/questions/11621740/how-to-determine-whether-a-year-is-a-leap-year-in-python?rq=1) –