Python programs / Numbers / Leap year check

Python Program to Check a Leap Year

Beginner Numbers

Checks whether a year is a leap year: divisible by 4, except century years, which must be divisible by 400.

A leap year has 366 days, with an extra day on 29 February. The Earth takes about 365.24 days to go round the Sun, so a leap day every 4 years would add slightly too much: the Gregorian calendar drops 3 leap years in every 400. The rule is that a year is a leap year if it's divisible by 4, except a century year, which must also be divisible by

  1. So 2024 is a leap year, 1900 isn't, and 2000 is.

Program

def is_leap_year(year):
    """True if year is a leap year in the Gregorian calendar."""
    if year % 400 == 0:
        return True
    if year % 100 == 0:
        return False
    return year % 4 == 0


print("2024:", is_leap_year(2024))
print("1900:", is_leap_year(1900))
print("2000:", is_leap_year(2000))

Open in the editor Download leap_year.py

Output

2024: True
1900: False
2000: True

How it works

  1. A year divisible by 400, such as 2000, is always a leap year. This test comes first because such a year is also divisible by 100, and the next test would wrongly turn it down.
  2. Any other year divisible by 100, such as 1900, is not a leap year.
  3. Every other year is a leap year when it's divisible by 4. year % 4 == 0 is already True or False, so the function returns it as it is, with no if.
  4. The program checks one year for each rule: 2024 (divisible by 4), 1900 (a century year) and 2000 (divisible by 400).

Other ways to write it

In one condition

The three rules fit in one condition with and and or (booleans). Read it as: divisible by 4, and either not a century year or divisible by 400. The brackets matter, as and is worked out before or.

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

print(is_leap_year(2024), is_leap_year(1900), is_leap_year(2000))

With the calendar module

Python's standard library already knows the rule: calendar.isleap().

import calendar

print(calendar.isleap(2024), calendar.isleap(2100))

Try it yourself

  • Check 2023, which isn't divisible by 4, and 2100, the next century year that isn't a leap year.
  • Print the leap years from 1990 to 2030 with a loop: there are 10.
  • Count the leap years from 2001 to 2400. There are 97, not 100, as 2100, 2200 and 2300 aren't leap years.
  • Write days_in_february(year), which returns 29 or 28.

More numbers programs

Share this program