Determining whether a year is a leap year or not is a common task in calendar-related operations in programming. Leap years are those years that are divisible by 4, except for years which are both divisible by 100 and not divisible by 400. This calculation ensures correct alignment with the astronomical and seasonal year.
In this article, you will learn how to check if a given year is a leap year using Python. By exploring practical examples, you'll understand how to implement this logic in your Python programs effectively.
Accept a year as input from the user.
Apply the leap year conditions using conditional statements.
Display the result based on the evaluation.
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.")
This code takes a year as input and checks the leap year conditions. If the year is divisible by 4 and not by 100, or if it is divisible by 400, it is identified as a leap year. Otherwise, it is not.
Define a function to encapsulate the leap year logic.
Use this function to check multiple years easily.
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
# Example Usage
years = [1996, 2000, 1900, 2021]
for year in years:
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
This snippet defines a is_leap_year
function that returns True
if the passed year is a leap year and False
otherwise. The function is then used to check a list of years and print whether each year is a leap year.
Checking whether a year is a leap year in Python can be easily implemented using basic arithmetic operations and conditional statements. By abstracting this logic into a function, you enhance code reusability and maintainability. Use these examples as a starting point to integrate leap year calculations into your Python applications, ensuring accurate date and time handling in various functionalities.