steve
steve

Reputation: 31

What should I do to this code to check leap years after 1900?

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

Answers (3)

Bemnet16
Bemnet16

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

MH Sumon
MH Sumon

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

aventurin
aventurin

Reputation: 2203

The condition

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

is wrong. Change your code such that

  1. year % 400 == 0 leap year
  2. year % 100 == 0 not a leap year
  3. year % 4 == 0 leap year
  4. all other: not a leap year

You could also use this algorithm: https://en.wikipedia.org/wiki/Leap_year#Algorithm

Upvotes: 1

Related Questions