Leap Year in Python

What is a Leap Year ?

A leap year occurs every four years to ensure that the calendar year aligns with the astronomical year. Normally, a year has 365 days, but the Earth’s orbit around the sun takes approximately 365.2422 days. To account for this extra fraction of a day, an additional day is added to the calendar every four years.

Leap Year Program in Python

Python, being a versatile programming language, provides us with an easy way to identify leap years. Let’s explore a simple algorithm to determine whether a given year is a leap year:

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

print(is_leap_year(2000))  # Output: True (divisible by 400)
print(is_leap_year(2020))  # Output: True (divisible by 4 but not by 100)
print(is_leap_year(1900))  # Output: False (divisible by 100 but not by 400)
print(is_leap_year(2023))  # Output: False (not divisible by 4)
leap year in Python

Leap Year by Using Python’s Calendar Module

Python’s calendar module simplifies leap year identification through its built-in functions. The isleap() function within the module can determine whether a given year is a leap year or not.

Here’s how we can use the isleap() function

import calendar

def is_leap_year(year):
    return calendar.isleap(year)

print(is_leap_year(2000))  # Output: True (divisible by 400)
print(is_leap_year(2020))  # Output: True (divisible by 4 but not by 100)
print(is_leap_year(1900))  # Output: False (divisible by 100 but not by 400)
print(is_leap_year(2023))  # Output: False (not divisible by 4)
Leap year program

See Also

Leave a Comment