Home > Blockchain >  Leap year program doing wrong things for a specific input
Leap year program doing wrong things for a specific input

Time:12-09

So I got this question from my friend yesterday regarding a program to check if a year is leap or not using python and decided to help. I wrote it up and it seems to run just fine until I enter 1992 as an input in which case it returns false (which shouldn't be the case). So I'm wondering where I wrong.

My code : `

def is_leap(year):
   leap = False

   if (year % 4) == 0:
       if (year % 100) == 0:
           if (year % 400) == 0:
               leap = True
           else:
               leap = False
       else:
           leap = False
   else:
       leap = False

   return leap

year = int(input())
print(is_leap(year))

Results : 1992 - > False

CodePudding user response:

Few problems with your code: first of all I would do checks in a partially reverse order, e.g.

  1. start checking year % 400,

  2. then in your line 5 you have a logical error: it has to be

    if not (year % 100) == 0:

  3. only then check for year % 4

The code can look like:

def is_leap(year):
    leap = False

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

year = int(input())
print(is_leap(year))

CodePudding user response:

The issue lies in the nested if statements. Leapyears are either year % 100 != 0 and year % 4 == 0 or year % 400 == 0.

Try this:

def is_leap(year):
    leap = False
    if year % 100 != 0 and year % 4 == 0 or year % 400 == 0:
        leap = True 

    return leap

year = int(input())
print(is_leap(year))
  • Related