To determine if a specific year is a leap year (a year with February 29th) in Python, use the isleap() function from the calendar module.
Using this function eliminates the need to write complex logic yourself (such as “divisible by 4, but not by 100, unless divisible by 400”).
Implementation Example: Checking Future Leap Years
Here, we create a script that checks a list of years to see if each is a leap year or a common year. We will specifically verify if it correctly handles edge cases like the year 2100 (which is a common year because it is divisible by 100).
Source Code
import calendar
# List of years to check
# 2024: Leap year
# 2025: Common year
# 2100: Divisible by 4 but also by 100, so "Common year"
years_to_check = [2024, 2025, 2100, 2000]
print("--- Leap Year Check Results ---")
for year_val in years_to_check:
# calendar.isleap(year) returns True for a leap year, False for a common year
is_leap = calendar.isleap(year_val)
# Output results clearly
if is_leap:
print(f"{year_val}: Leap year (True)")
else:
print(f"{year_val}: Common year (False)")
Execution Result
--- Leap Year Check Results ---
2024: Leap year (True)
2025: Common year (False)
2100: Common year (False)
2000: Leap year (True)
Explanation
calendar.isleap(year)
When you pass a year (integer) as an argument, it returns a boolean value (True or False). If the return value is True, the year has 366 days and includes February 29th.
Checking the Current Year
If you want to check the current year, combine it with the datetime module as follows:
from datetime import datetime
import calendar
# Get current year
current_year = datetime.now().year
# Execute check
if calendar.isleap(current_year):
print("This year is a leap year.")
else:
print("This year is a common year.")
