Leap years in a range given as text
Write a Python program to count the leap years in a range given as a string like “1981-2001”.
"1981-2001"
Total leap years: 5 [1984, 1988, 1992, 1996, 2000]
Approach
- Split the text, convert both years, count with
calendar.isleap.
Solution
import calendar text = "1981-2001"start, end = map(int, text.split("-"))leaps = [y for y in range(start, end + 1) if calendar.isleap(y)]print("Total leap years:", len(leaps), leaps)Total leap years: 5 [1984, 1988, 1992, 1996, 2000]
Line by line
map(int, ...) converts both parts.
Learn the concept
New to this topic? Read the lesson, then come back.