Python Practice › Basic Programs › Program 29
Check a leap year
Write a Python program to check whether a year is a leap year: divisible by 4, except century years, which must be divisible by 400.
Input
1900, 2000, 2024, 2026
Output
1900 not leap 2000 leap 2024 leap 2026 not leap
Approach
- Combine the rules with
and/or.
Solution 1: the rules
for year in [1900, 2000, 2024, 2026]: leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 print(year, "leap" if leap else "not leap")Output
1900 not leap 2000 leap 2024 leap 2026 not leap
Line by line
Line 2
Divisible by 4 but not by 100, or divisible by 400.
Solution 2: calendar module
import calendarprint([y for y in [1900, 2000, 2024, 2026] if calendar.isleap(y)])Output
[2000, 2024]
Line by line
Line 2
calendar.isleap() implements the same rules.
Learn the concept
New to this topic? Read the lesson, then come back.