Python Practice › String Programs › Program 87
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”.
Input
"1981-2001"
Output
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)Output
Total leap years: 5 [1984, 1988, 1992, 1996, 2000]
Line by line
Line 4
map(int, ...) converts both parts.
Learn the concept
New to this topic? Read the lesson, then come back.