View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Leap Year Program in Python

Updated on 22/01/202515,266 Views

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!

How to Check Leap Year in Python

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.

Divisibility Conditions to Check Leap Year in Python

To determine whether a year is a leap year, specific divisibility rules must be followed:

  • Divisible by 4: The primary rule states that any year that is evenly divisible by 4 is a leap year. For example, years like 2020 and 2016 are leap years because they can be divided by 4 without a remainder.
  • Divisible by 100: However, if the year is divisible by 100, it is not automatically considered a leap year. For instance, the year 1900 is divisible by 100 but is not a leap year because it does not meet the next condition.
  • Divisible by 400: If a year is divisible by both 100 and 400, then it is classified as a leap year. For example, the year 2000 is a leap year because it meets this criterion (divisible by both 100 and 400), while the year 1900 does not qualify as it is only divisible by 100

Examples of Leap Years

Leap Years:

  • 2000: Divisible by both 100 and 400.
  • 2016: Divisible by 4 but not by 100.
  • 2020: Divisible by 4 but not by 100.

Non-Leap Years:

  • 1900: Divisible by 100 but not by 400.
  • 2100: Divisible by 100 but not by 400.
  • 2019: Not divisible by 4.

Summary of Leap Year Condition in Python

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

7 Different Methods to Check Leap Year in Python

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.

Performance Analysis of Different Methods Using Time Complexity and Space Complexity

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.

How upGrad can help you?

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

FAQ’s

1. What are the different methods to check if a year is a leap year in Python?

There are 7 different methods to check if a year is a leap year in Python:

  1. If-else statement: A simple condition-based approach.
  2. Nested if-else: Adds hierarchical logic for conditions.
  3. Ternary Operator: A concise single-line implementation.
  4. For Loops: Checks the condition in an iterative structure (less commonly used for leap year logic).
  5. While Loop: Also iterative, can be used for continuous user input.
  6. Python Libraries - calendar.isleap(): A built-in function for checking leap years.
  7. Lambda Function: A compact, functional programming approach for leap year verification.

2. How can you use the calendar module to determine leap years 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:

  • Simplifies the implementation.
  • Highly reliable and optimized for performance.
  • Can be used in scenarios requiring leap year checks in multiple places.

3. What’s the logic behind the leap year conditions in Python?

The logic is based on the Gregorian calendar rules:

1. A year is a leap year if:

    • It is divisible by 4.
    • But not divisible by 100, unless it is also divisible by 400.

2. Mathematically, the conditions can be expressed as:(year % 4 == 0) and (year % 100 != 0 or year % 400 == 0)

Explanation:

  • Years divisible by 4 are typically leap years.
  • However, years divisible by 100 are not leap years (e.g., 1900 is not a leap year).
  • Exception: Years divisible by 400 are leap years (e.g., 2000 is a leap year).

4. What are some advanced techniques for writing a leap-year program in Python?

Advanced techniques for implementing leap year programs include:

  1. Lambda Functions:
  • Use a functional programming approach for compact code.

is_leap = lambda year: (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0)

print(is_leap(2024))

  1. Using the calendar module:
    • Leverage the built-in isleap() method for reliability and reusability.
  2. List Comprehension:
    • Generate a list of leap years from a given range of years.

leap_years = [year for year in range(2000, 2100) if calendar.isleap(year)]

print(leap_years)

  1. Integration with Datetime:
    • Combine leap year checks with other date-related functionalities for robust date validation systems.
  2. Handling User Input with While Loops:
    • Use loops to validate user input and re-prompt until valid input is provided.

5. How can you use a while loop to validate user input for a leap-year program?

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:

  • Ensures robust input handling.
  • Prevents crashes due to invalid input (e.g., strings or negative numbers).
  • Enhances user experience by prompting for corrections.

Ready to challenge yourself? Take our Free Python Quiz!

image
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.