PythonMastery

Leap year program in Python

Check whether a year is a leap year: divisible by 4, except years divisible by 100, unless they are also divisible by 400.

A year is a leap year if it divides by 4, except years that divide by 100, which are leap years only if they also divide by 400. So 2024 is a leap year, 1900 is not, and 2000 is.

The program

python
year = int(input("Year: "))

if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(f"{year} is a leap year")
else:
    print(f"{year} is not a leap year")

Typed in this example: 1900. Press Run to type your own.

output
Year: 1900
1900 is not a leap year

How it works

Checking several years

The standard library already has this rule, in the calendar module:

python
import calendar

for year in [2023, 2024, 1900, 2000]:
    print(year, calendar.isleap(year))
output
2023 False
2024 True
1900 False
2000 True

Learn the idea: Control Flow: Conditionals, Operators & Expressions