Prompt
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
- Imports: No external libraries are needed for this operation.
- Documentation Block: Clearly explains the function’s purpose, parameters, return type, and possible exceptions.
- Input Validation: Ensures the input is a positive integer. If not, raises a
ValueError
. - 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.
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.
More Code Generators
Apache Flink Code Generator Apache Pig Code Generator Azure Data Factory Code Generator C/C++ Code Generator CouchDB Code Generator DAX Code Generator Excel Code Generator Firebase Code Generator Google BigQuery Code Generator Google Sheets Code Generator GraphQL Code Generator Hive Code Generator Java Code Generator JavaScript Code Generator Julia Code Generator Lua Code Generator M (Power Query) Code Generator MATLAB Code Generator MongoDB Code Generator Oracle Code Generator PostgreSQL Code Generator Power BI Code Generator Python Code Generator R Code Generator Redis Code Generator Regex Code Generator Ruby Code Generator SAS Code Generator Scala Code Generator Shell Code Generator SPSS Code Generator SQL Code Generator SQLite Code Generator Stata Code Generator Tableau Code Generator VBA Code Generator