Python Practice › String Programs › Program 87

Leap years in a range given as text

EasyString Programs · 87 of 106

Write a Python program to count the leap years in a range given as a string like “1981-2001”.

Advertisement
Input
"1981-2001"
Output
Total leap years: 5 [1984, 1988, 1992, 1996, 2000]

Approach

  1. Split the text, convert both years, count with calendar.isleap.

Solution

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

More string programs

← All 106 String Programs

Leave a Comment