HappyHands31 - 6 months ago 52

Python Question

We know it's a leap year if it's divisible by four and, if it's a century year, it's divisible by 400. I thought I would need two If Statements like this:

`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)

When I tried the code above I got error messages for the years

`1800 - Test Failed: expected False but got True`

1900 - Test Failed: expected False but got True

Basically I need my code to say that "the test is true if the year is divisible by four, and, if it's a century year, it's divisible by 400." But when I try:

`if n % 4 and (n % 100 == 0 and n % 400 == 0):`

return True

else:

return False

I get three error messages (for the years)

`1944 - Test Failed: expected True but got False`

1956 - Test Failed: expected True but got False

2056 - Test Failed: expected True but got False

So it looks like me creating the second condition (divisible by 100 and 400) has canceled out the years that are divisible by 4.

Answer

try this:

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

The problem is that you want the year to be divisible cleanly by 4 OR by 400 if it's a century year.

```
>>> [(x % 100 != 0 and x % 4 == 0) or x % 400 == 0 for x in [1944, 1956, 2056, 1800, 1900]]
[True, True, True, False, False]
```