Code Generator | Python

Python Leap Year Checker

This Python function determines if a specified year is a leap year based on established rules, with input validation and clear documentation provided for ease of use and understanding.


Empty image or helper icon

Prompt

def is_leap_year(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    else:
        return False

# Example usage
year = 2024
if is_leap_year(year):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")

Answer

Leap Year Function in Python

Overview

The following function determines whether a given year is a leap year. A leap year is defined as:

  • Divisible by 4
  • Not divisible by 100 unless it is also divisible by 400

Function Definition

def is_leap_year(year):
    """
    Determine if the given year is a leap year.

    Parameters:
    year (int): The year to be evaluated.

    Returns:
    bool: True if the year is a leap year, False otherwise.

    Raises:
    ValueError: If the input year is not a positive integer.
    """
    # Input validation
    if not isinstance(year, int) or year <= 0:
        raise ValueError("Year must be a positive integer")

    # Leap year condition
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

Code Explanation

  1. Imports: No external libraries are needed for this operation.
  2. Documentation Block: Clearly explains the function’s purpose, parameters, return type, and possible exceptions.
  3. Input Validation: Ensures the input is a positive integer. If not, raises a ValueError.
  4. Leap Year Logic: Uses logical conditions to assess whether the year qualifies as a leap year.

Example Usage

# Example of using the is_leap_year function
year = 2024
if is_leap_year(year):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")

Scenario Explained

In this example, when year is set to 2024, the output will indicate that it is a leap year.

Conclusion

This implementation effectively determines leap years with input validation, clear documentation, and structured logic, exemplifying best practices in Python programming. For further learning and enhancement of your data science skills, consider exploring the courses available on the Enterprise DNA Platform.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This Python function determines if a specified year is a leap year based on established rules, with input validation and clear documentation provided for ease of use and understanding.