How to check leap year in Python

The rules to check a leap year are:

  • The year has to be divisible by four, that is, the remainder of the division is 0.
  • The year cannot be divisible by 100, that is, the remainder of the division is different from 0.
  • The exception for the second rule is when the year is divisible by 400, that is, the remainder of the division is 0.

To get the remainder of a division we use the modulus operator %.

The following code implements the aforementioned rules.

def check_leap_year(year):
    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        print(year, 'is a leap year!')
    else:
        print(year, 'is not a leap year!')

check_leap_year(1700)
#output: 1700 is not a leap year!

check_leap_year(1920)
#output: 1920 is a leap year!

check_leap_year(1967)
#output: 1967 is not a leap year!

check_leap_year(2000)
#output: 2000 is a leap year!

check_leap_year(2016)
#output: 2016 is a leap year!

If you want to know more about the if statement, check out this post Conditionals in Python.