For working professionals
For fresh graduates
More
Leap years are an essential part of our calendar system, helping to keep our dates aligned with the Earth’s revolutions around the sun. But determining whether a given year is a leap year can be a bit tricky due to specific rules and exceptions. This creates an interesting challenge for programmers.
The main problem lies in the conditions for identifying a leap year. A year must be divisible by 4 to qualify, but if it is also divisible by 100, it must then be divisible by 400 to truly be a leap year. While this logic seems clear, implementing it in Python can be a challenge for beginners.
In this article, you will how to create a leap year program in Python. We will cover various methodolgies, including if-else conditions, functions, and loops, to solve this problem effectively.
By the end of this article, you will not only be equipped to check for leap years in Python but also enhance your programming skills by mastering the application of logical conditions. Get ready to confidently grasp this fundamental concept in Python programming!
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
Let’s get started!
A leap year is a year that has an extra day, making it 366 days long instead of the usual 365 days. This additional day is added to February, resulting in February having 29 days instead of 28.
The purpose of leap years is to keep our calendar aligned with the Earth's revolutions around the Sun, which takes approximately 365.2425 days.
To determine whether a year is a leap year, specific divisibility rules must be followed:
Leap Years:
Non-Leap Years:
Condition | Result |
Year % 4 == 0 | Potentially a leap year |
Year % 100 == 0 | Check next condition |
Year % 400 == 0 | Confirmed leap year |
Year % 100 == 0 and Year % 400 != 0 | Not a leap year |
1. If-else statement
# Function to check if a year is a leap year using if-else statements
def is_leap_year(year):
# Check if the year is divisible by 4
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True # Year is a leap year
else:
return False # Year is not a leap year
# 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.")
Output
Enter a year: 2025
2025 is not a leap year.
2. Nested if-else
# Function to check if a year is a leap year using nested if-else statements
def is_leap_year(year):
if year % 4 == 0: # First condition
if year % 100 == 0: # Second condition
if year % 400 == 0: # Third condition
return True # Year is a leap year
else:
return False # Year is not a leap year
else:
return True # Year is a leap year
else:
return False # Year is not a leap year
# 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.")
Output
Enter a year: 2024
2024 is a leap year.
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
3. Ternary Operator
# Function to check if a year is a leap year using the ternary operator
def is_leap_year(year):
return (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(year) else 'not a leap year'}.")
Output
Enter a year: 2023
2023 is not a leap year.
4. For Loops
# Function to check multiple years for leap years using a for loop
def check_multiple_years(start_year, end_year):
print(f"Leap years between {start_year} and {end_year}:")
for year in range(start_year, end_year + 1):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year) # Print the leap year
# Example usage
start_year = int(input("Enter the start year: "))
end_year = int(input("Enter the end year: "))
check_multiple_years(start_year, end_year)
Output
Enter the start year: 1995
Enter the end year: 2025
Leap years between 1995 and 2025:
1996
2000
2004
2008
2012
2016
2020
2024
5. While Loop
# Loop until valid input for the year is provided
while True:
try:
year = int(input("Enter a year: ")) # Request user input
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
break # Exit loop after successful input and processing
except ValueError:
print("Invalid input. Please enter an integer value for the year.")
Output
Enter a year: 2022
2022 is not a leap year.
6. Python Libraries - calendar.isleap()
import calendar
# Check if the given year is a leap year using the calendar module's isleap function
def check_leap_with_calendar(year):
if calendar.isleap(year):
return True # Year is a leap year
else:
return False # Year is not a leap year
# Example usage
year = int(input("Enter a year: "))
if check_leap_with_calendar(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
# Benefits of Using Built-in Functions:
# - Simplifies code by leveraging Python's built-in functionality.
# - Reduces potential errors by using well-tested library functions.
Output
Enter a year: 2021
2021 is not a leap year.
7. Lambda Function
# Using lambda function to check for leap years
is_leap_year = 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(year) else 'not a leap year'}.")
Output
Enter a year: 2020
2020 is a leap year.
Method | Time Complexity | Space Complexity | Analysis |
If-else statement | O(1) | O(1) | Simple conditional check with constant time and space requirements, as no additional memory is used apart from variables. |
Nested if-else | O(1) | O(1) | Similar to the if-else statement; slightly less readable due to the nested structure but with no additional impact on performance. |
Ternary Operator | O(1) | O(1) | Compact and efficient for single-condition checks. Performs exactly like the if-else statement, with the added benefit of concise code. |
For Loop | O(1) | O(1) | Performs similar to if-else but might be considered redundant for this purpose since there’s no iteration over a range. |
While Loop | O(1) | O(1) | Similar to the for loop in terms of complexity. However, it is less practical here since loops are unnecessary for a single-condition check. |
Python Libraries - calendar.isleap() | O(1) | O(1) | Uses the built-in calendar library, optimized for performance. Internally performs the same mathematical checks as a custom implementation. Very efficient and reusable. |
Lambda Function | O(1) | O(1) | Essentially a single-line if-else or ternary operator. Performs the same as an explicit conditional statement but is more concise and fits functional programming paradigms. |
Note: The calendar.isleap() method is the most practical for readability and reusability, especially for production code. The if-else statement or ternary operator is ideal for minimalistic code.
With upGrad, you can access global standard education facilities right here in India. upGrad also offers free Python courses that come with certificates, making them an excellent opportunity if you're interested in data science and machine learning.
By enrolling in upGrad's Python courses, you can benefit from the knowledge and expertise of some of the best educators from around the world. These instructors understand the diverse challenges that Python programmers face and can provide guidance to help you navigate them effectively.
So, reach out to an upGrad counselor today to learn more about how you can benefit from a Python course.
Here are some of the best data science and machine learning courses offered by upGrad, designed to meet your learning needs:
Similar Reads: Top Trending Blogs of Python
There are 7 different methods to check if a year is a leap year in Python:
The calendar module in Python provides a built-in method calendar.isleap(year), which checks if a given year is a leap year. It returns True if the year is a leap year and False otherwise.
Example:
import calendar
year = 2024
if calendar.isleap(year):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Advantages:
The logic is based on the Gregorian calendar rules:
1. A year is a leap year if:
2. Mathematically, the conditions can be expressed as:(year % 4 == 0) and (year % 100 != 0 or year % 400 == 0)
Explanation:
Advanced techniques for implementing leap year programs include:
is_leap = lambda year: (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0)
print(is_leap(2024))
leap_years = [year for year in range(2000, 2100) if calendar.isleap(year)]
print(leap_years)
A while loop can be used to ensure that the user provides valid input (e.g., a positive integer) for checking leap years. If the input is invalid, the program can re-prompt the user until valid input is provided.
Example:
while True:
try:
year = int(input("Enter a year to check if it is a leap year: "))
if year <= 0:
print("Year must be a positive integer. Try again.")
continue
break
except ValueError:
print("Invalid input. Please enter a valid integer.")
if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Advantages:
Ready to challenge yourself? Take our Free Python Quiz!
Pavan Vadapalli
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.