Basics · beginner
Python Program to Check Leap Year
Check whether a year is a leap year in Python with the full rule (divisible by 4, but centuries only when divisible by 400), and compare with calendar.isleap().
- modulo operator %
- and / or
- functions
- calendar module
A leap year has 366 days. The rule has three parts: a year divisible by 4 is a leap year, except years divisible by 100, which are not, except years divisible by 400, which are. So 2024 and 2000 are leap years, but 1900 and 2100 are not.
Many quick solutions only check the first part, which gives the wrong answer for 1900. The function below handles all three.
The program
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
for year in [2024, 2023, 1900, 2000]:
print(year, "is a leap year" if is_leap(year) else "is not a leap year")2024 is a leap year
2023 is not a leap year
1900 is not a leap year
2000 is a leap yearHow it works
- year % 4 == 0 keeps only years divisible by 4.
- The part in brackets accepts the year if it is not a century (year % 100 != 0) or if it is a century divisible by 400.
- and needs both parts to be True, so 1900 fails (divisible by 100, not by 400) and 2000 passes.
- The function returns a boolean, and the conditional expression in print turns it into a sentence.
Watch it run line by line
Each call to is_leap opens a new frame with its own year variable, and the return row shows True or False before the loop prints the sentence.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: With the calendar module
The standard library already implements the rule. calendar.isleap() is the safest choice in real programs, and calendar.leapdays() counts leap years in a range.
import calendar
print(calendar.isleap(1900), calendar.isleap(2000))
print(calendar.leapdays(2000, 2025))False True
7Common mistakes
- Checking only year % 4 == 0, which wrongly makes 1900 and 2100 leap years.
- Mixing up the brackets: without them, and binds tighter than or, so the condition means something different.
- calendar.leapdays(y1, y2) does not include y2 itself, which surprises people counting up to a leap year.
Try it yourself
- Print every leap year between 1890 and 1920.
- Write the same rule as nested if statements and check that both versions agree for every year from 1 to 3000.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.