Check If Its A Leap Year With Python

Learn python programming in 12 lessons


Most people know that that we have a leap year every fourth year but that is not exactly accurate. To understand the properties of a leap year, you would want to look up some facts on leap year on math is fun.

The main properties of a leap year are
  1. it is evenly divided by 4 meaning no remainder
  2. if condition 1 passes, then it should not be evenly divisible by 100
  3. it is evenly divisible by 400
In other words, a year is a leap year if it is evenly divisible by 4 or 400 and not evenly divisible by 100. That statement is going to makeup the the if statement in the Python program. Notice that the year 2000 is a leap year and so is 1600 and 2400 but not 1700, 1800, 1900, 2100, 2200, 2300. An extra condition is needed to compensate for this anomaly otherwise we might disregard the year 1600, 2000 and 2400 as not leap years.

The Python function can look something like this


# This function checks if the year is a leap year
def leapYear(year):
   
    # make sure the parameter is an integer
    year = int(year)
   
    # A year is a leap year if it is divisible by 400 or 4 and not by 100
    if (year%400 == 0 or year%4 ==0) and year%100 !=0:
        print(year,"is a leap year.")
    else:
        print(year,"is not a leap year.")

Share your thoughts