Program to Check if a Year is a Leap Year in Python
Checking Leap Year
A leap year is a year that is evenly divisible by 4, except for years that are evenly divisible by 100. However, years divisible by 400 are also considered leap years.
We will explore different methods to check if a year is a leap year using Python programming.
Method 1: Using if-else Statement
We use an if-else statement to check if a year satisfies the leap year conditions.
year = int(input("Enter a year: ")) 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")
Output:
Enter a year: 2024 2024 is a leap year
Method 2: Using Ternary Operator
We use the ternary operator to check leap year conditions in a single line.
year = int(input("Enter a year: ")) print(f"{year} is a leap year" if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else f"{year} is not a leap year")
Output:
Enter a year: 2023 2023 is not a leap year
Method 3: Using Function
We create a function to check if a year is a leap year and return the result.
def is_leap_year(year): return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) 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: 2000 2000 is a leap year