Write a Python function to check if a given year is a leap year.
Posted by PaulAnd
Last Updated: August 09, 2024
Checking for Leap Years in Python
Leap years are an essential concept in the Gregorian calendar, occurring every four years to help synchronize the calendar year with the astronomical year. A year is considered a leap year if it meets the following conditions: 1. The year is divisible by 4. 2. If the year is divisible by 100, it must also be divisible by 400 to be a leap year. Using these rules, a Python function can be created to determine if a given year is a leap year. Below is a simple implementation of this logic:
def is_leap_year(year):
    """
    Function to check if a given year is a leap year.

    Parameters:
    year (int): The year to be checked

    Returns:
    bool: True if the year is a leap year, False otherwise
    """
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    else:
        return False

# Example usage:
year_to_check = 2024
if is_leap_year(year_to_check):
    print(f"{year_to_check} is a leap year.")
else:
    print(f"{year_to_check} is not a leap year.")
Explanation of the Code
- The function is_leap_year takes a single parameter year, which is of integer type. - It uses the conditional logic to check the divisibility of the year: - It first checks if the year is divisible by 4 and not divisible by 100, which would imply it is a leap year. - It also checks if the year is divisible by 400, confirming that it is a leap year despite being divisible by 100. - The function returns True if either condition for a leap year is satisfied, otherwise, it returns False.
Example
To use this function, simply call it with an integer representing the year you wish to check. The example provided checks the year 2024 and prints whether it is a leap year or not. This function can be easily incorporated into larger programs where date calculations are necessary, ensuring accurate handling of leap years.