Leap Year Checker Program in Python
This document provides a Python program to determine whether a given year is a leap year. A leap year is a year that is divisible by 4, but years divisible by 100 are not leap years unless they are also divisible by 400.
Program Structure
The program follows these steps:
- Accepts a year as input from the user.
- Checks if the year is divisible by 4.
- If the year is divisible by 4, further checks if it is also divisible by 100.
- If the year is divisible by 100, checks if it is also divisible by 400.
- Prints whether the year is a leap year or not based on the conditions.
Python Code
def is_leap_year(year):
"""
Check if a given year is a leap year.
A year is a leap year if:
- It is divisible by 4, and
- It is not divisible by 100, unless
- It is also divisible by 400.
Args:
year (int): The year to check.
Returns:
bool: True if the year is a leap year, False otherwise.
"""
if (year % 4 == 0):
if (year % 100 == 0):
if (year % 400 == 0):
return True
else:
return False
else:
return True
else:
return False
def main():
"""
Main function to execute the leap year checker.
"""
try:
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.")
except ValueError:
print("Please enter a valid integer year.")
if __name__ == "__main__":
main()
Explanation
The is_leap_year
function implements the leap year logic:
- If a year is divisible by 4, it’s a potential leap year.
- If it’s also divisible by 100, it must be divisible by 400 to be a leap year.
- Otherwise, it’s not a leap year.
The main
function handles user input and output:
- It prompts the user to enter a year.
- It calls the
is_leap_year
function and prints whether the year is a leap year. - It includes error handling for invalid input.