Python Practice › Basic Programs › Program 29

Check a leap year

EasyBasic Programs · 29 of 40

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.

Advertisement
Input
1900, 2000, 2024, 2026
Output
1900 not leap
2000 leap
2024 leap
2026 not leap

Approach

  1. Combine the rules with and / or.

Solution 1: the rules

Python
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

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs