Search code examples
pythonpython-importleap-year

Use Calendar function for leap year


I'm trying to use the import function to calculate my leap year, however I've been getting error messages for my code:

import calendar
year=input("Enter a year: ")
check=calendar.isleap(year)
if check == True:
    print("In",year,"February has 29 days.")
else:
    print("In",year,"February has 28 days.")

Would appreciate it if anyone can point out my mistake here!

I've also tried the

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

method by using 'if-else' statements, but have also seem to stumble onto a roadblock using that method as well...My code for that method is shown below:

print ('hi')
input_year= input("Please enter a year: ")
if (input_year) % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print ("Yes sir")
else:
    print ("no sir")

Solution

  • Python 2 will automatically attempt to convert the string the user typed into a number and return an int from the input function if it can. But Python 3 will be more consistent and always return a string even if the characters the user typed are logically understood to be a number.

    Hence, do this:

    import calendar
    year=input("Enter a year: ")
    year = int(year)
    check=calendar.isleap(year)
    if check:
        print("In",year,"February has 29 days.")
    else:
        print("In",year,"February has 28 days.")