Python programs · Basics
Python program to check a leap year
A leap year has 366 days. The rule has three parts, and the order of the tests matters.
Approach
- A year divisible by 4 is a leap year...
- ...unless it is divisible by 100...
- ...except that years divisible by 400 are leap years again.
The program
year = int(input()) 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")
Sample run
Input
2024
Output
2024 is a leap year
How the code works
The condition says: divisible by 4 and not by 100, or divisible by 400. So 2024 (divisible by 4, not by 100) is a leap year, 1900 (divisible by 100 but not by 400) is not, and 2000 (divisible by 400) is.
Try changing it
- Print every leap year between two years with a
forloop. - Turn the test into a function
is_leap(year)that returnsTrueorFalse.
Common mistakes
- Testing only
year % 4 == 0, which wrongly accepts 1900. - Forgetting the rule for 400, which wrongly rejects 2000.