Reputation: 31
def is_leap(year):
leap = False
if(( year % 400 == 0 and year % 100 == 0 ) or ( year % 4 ==0 )):
leap = True
# Write your logc here
return leap
year = int(input())
print(is_leap(year))
I used this code to find leap years after 1900 for the HackerRank python 'write a function' exercise, but it shows the wrong result for the year 2100.
What should I do?
Upvotes: 0
Views: 88
Reputation: 13
This is because your condition year % 4 == 0
is evaluating to True for the year 2100, which is not divisible by 400 but divisible by 100 and 4.
The condition should be (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
:
def is_leap(year):
leap = False
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
leap = True
return leap
year = int(input())
print(is_leap(year))
Upvotes: 0
Reputation: 1
def is_leap(year): leap = False
if year % 400 == 0:
leap = True
elif year % 100 == 0:
leap = False
elif year % 4 == 0:
leap = True
return leap
year = int(input()) print(is_leap(year))
Upvotes: -3
Reputation: 2203
The condition
( year % 400 == 0 and year % 100 == 0 ) or ( year % 4 ==0 )
is wrong. Change your code such that
year % 400 == 0
leap yearyear % 100 == 0
not a leap yearyear % 4 == 0
leap yearYou could also use this algorithm: https://en.wikipedia.org/wiki/Leap_year#Algorithm
Upvotes: 1