Editor

Python Program to Check a Leap Year

Beginner · Basics

A leap year has 366 days instead of 365, with an extra day on 29 February. A year is a leap year if it divides evenly by 4, except century years like 1900, which are leap years only if they also divide evenly by 400. This program applies that rule to a year.

Program

leap_year.py
year = 2024 # or: year = int(input("Enter a year: "))
# Divisible by 4 is a leap year, except century years,
# which must also be divisible by 400.
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")
Output
2024 is a leap year

How it works

  1. year % 4 == 0 checks whether the year divides evenly by 4, the basic leap year rule.
  2. year % 100 != 0 leaves out century years such as 1900 and 2100, which are usually not leap years.
  3. year % 400 == 0 brings back the century years that divide by 400, such as 2000.
  4. The or joins the two cases, so the year is a leap year if either one is true.

Other ways to write it

Using nested if statements

Using nested if statements
year = 1900
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
else:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Output
1900 is not a leap year

Each if checks one part of the rule, which is longer but makes every step easy to follow.

Using calendar.isleap()

Using calendar.isleap()
import calendar
for year in [1900, 2000, 2023, 2024]:
if calendar.isleap(year):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Output
1900 is not a leap year
2000 is a leap year
2023 is not a leap year
2024 is a leap year

The standard calendar module already has a leap year check, handy when you need to test many years.

Try it yourself

Change the program to print every leap year from 1990 to 2030.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises