Working on a Python project that involved handling dates for a payroll system, I needed to determine whether a given year was a leap year or not.
At first glance, it seemed like a simple problem, but as a Python developer with over 10 years of experience, I know that even simple date-related logic can be tricky if not handled correctly.
So, in this tutorial, I’ll show you how to write a Leap Year Program in Python using a function, step by step. I’ll also share a few different methods, from using simple conditional statements to leveraging Python’s built-in calendar module, so you can choose whichever fits your use case best.
What Is a Leap Year?
Before we jump into the Python code, let’s quickly refresh what a leap year actually means.
A leap year is a year that has 366 days instead of 365, with an extra day (February 29). This adjustment keeps our calendar year synchronized with the Earth’s orbit around the sun.
In general, a year is a leap year if:
- It is divisible by 4, and
- It is not divisible by 100, unless
- It is also divisible by 400.
For example:
- 2020 → Leap Year
- 1900 → Not a Leap Year
- 2000 → Leap Year
Let’s now see how to implement this logic in Python.
Method 1 – Use an If-Else Function in Python
When I first started writing Python code, I preferred to keep things simple and readable. This method uses basic conditional statements inside a user-defined function.
Here’s how you can do it:
def is_leap_year(year):
"""Check if a given year is a leap year."""
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# Example usage
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a Leap Year!")
else:
print(f"{year} is not a Leap Year.")I executed the above example code and added the screenshot below.

This Python program defines a function is_leap_year() that takes a year as input and returns True if it’s a leap year, otherwise False. The condition (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) captures the exact leap year rule we discussed earlier.
Try entering years like 2024, 1900, and 2000 to see how it behaves.
Method 2 – Use Python’s calendar Module
When working on production-grade applications, I often rely on Python’s built-in modules to simplify my code. The calendar module includes a handy function called isleap() that does this check for you.
Here’s how you can use it:
import calendar
def check_leap_calendar(year):
"""Check leap year using Python's calendar module."""
return calendar.isleap(year)
# Example usage
year = int(input("Enter a year: "))
if check_leap_calendar(year):
print(f"{year} is a Leap Year (checked using calendar module).")
else:
print(f"{year} is not a Leap Year (checked using calendar module).")I executed the above example code and added the screenshot below.

This method is simpler and more reliable since it uses Python’s built-in logic. The calendar.isleap() function returns True if the year is a leap year, and False otherwise, perfect for quick checks in real-world projects.
Method 3 – Leap Year Program in Python Using Lambda Function
In some cases, especially when I’m writing compact scripts or using list comprehensions, I prefer using lambda functions.
Here’s how you can write a leap year check using a Python lambda function:
is_leap = lambda year: (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Example usage
year = int(input("Enter a year: "))
print(f"{year} is a Leap Year!") if is_leap(year) else print(f"{year} is not a Leap Year.")I executed the above example code and added the screenshot below.

This one-liner is perfect when you want a quick check without defining a full function. It’s also great for use inside a larger Python data-processing pipeline, like filtering leap years from a list of years.
Method 4 – Leap Year Program in Python Using Datetime Module
If your project involves working with actual date objects, the datetime module can also help determine leap years indirectly.
Here’s a neat trick I often use:
import datetime
def leap_year_datetime(year):
"""Check leap year using datetime by testing Feb 29."""
try:
datetime.date(year, 2, 29)
return True
except ValueError:
return False
# Example usage
year = int(input("Enter a year: "))
if leap_year_datetime(year):
print(f"{year} is a Leap Year (verified using datetime).")
else:
print(f"{year} is not a Leap Year (verified using datetime).")I executed the above example code and added the screenshot below.

In this method, we try to create a date object for February 29. If Python raises a ValueError, that means the year doesn’t have Feb 29, so it’s not a leap year.
This approach is intuitive and uses Python’s date validation system directly.
Bonus – Check Leap Years in a Range Using a Python Function
Sometimes, you may want to find all the leap years within a particular range, for instance, between 2000 and 2050.
Here’s a function that does exactly that:
def leap_years_in_range(start_year, end_year):
"""Return a list of leap years between two years."""
leap_years = []
for year in range(start_year, end_year + 1):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
leap_years.append(year)
return leap_years
# Example usage
print("Leap years between 2000 and 2050:")
print(leap_years_in_range(2000, 2050))This Python function loops through a range of years and collects all leap years in a list.
It’s perfect for generating reports, validating date ranges, or even creating test data for time-based applications.
Common Mistakes to Avoid When Writing a Leap Year Program in Python
Even though the logic seems simple, I’ve seen developers (including myself, early on) make a few common mistakes:
- Forgetting the 100-year rule – Many beginners check only if the year is divisible by 4.
- Not including the 400-year exception – Years like 2000 are leap years, even though they’re divisible by 100.
- Using integer division incorrectly – Always use
%(modulus) instead of/for divisibility checks. - Ignoring built-in modules – Don’t reinvent the wheel; Python’s
calendarand datetime modules are reliable and efficient.
By keeping these points in mind, your code will be both accurate and maintainable.
Real-World Use Case: Payroll and Scheduling Systems
In the U.S., many payroll and scheduling applications must account for leap years to calculate salary periods, tax filing dates, or employee benefits accurately.
For example, a system calculating biweekly pay might need to adjust for the extra day in February during a leap year.
Using a Python function like is_leap_year() ensures that your system automatically adapts without manual updates every four years.
Key Takeaways
- A leap year occurs every 4 years, except for years divisible by 100 (unless divisible by 400).
- You can easily check leap years in Python using:
- Simple conditional statements
- The calendar module (calendar.isleap())
- A lambda function for compact logic
- The datetime module for date-based validation
- Always test your code with edge cases like 1900, 2000, and 2024.
Python makes it simple, elegant, and reliable to handle leap year calculations — whether you’re building a small script or a large enterprise system.
I hope you found this tutorial on writing a Leap Year Program in Python using a function helpful.
Both beginners and experienced developers can benefit from understanding the logic behind leap years, especially when working with time-sensitive applications.
You may also read:
- Write a Python Program to Remove Duplicates From a Dictionary
- Python Create Empty Dictionary
- Check If Two Dictionaries Are Equal in Python
- Python Copy Dict Without One Key

Bijay Kumar is an experienced Python and AI professional who enjoys helping developers learn modern technologies through practical tutorials and examples. His expertise includes Python development, Machine Learning, Artificial Intelligence, automation, and data analysis using libraries like Pandas, NumPy, TensorFlow, Matplotlib, SciPy, and Scikit-Learn. At PythonGuides.com, he shares in-depth guides designed for both beginners and experienced developers. More about us.