How To Check A Year Is Leap Year In Python

You can check if a year is a leap year in Python using the following logic:

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

# Test the function
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.")
Code language: Python (python)

This code defines a function is_leap_year that takes a year as input and returns True if it’s a leap year and False if it’s not. The logic checks whether the year is divisible by 4 and not divisible by 100, or if it’s divisible by 400. If either of these conditions is met, the year is considered a leap year.

What is the formula for leap year in Python?

The formula to determine if a year is a leap year can be expressed in Python as follows:

def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
Code language: Python (python)

This concise formula uses the same logic as mentioned earlier: a leap year is either divisible by 4 and not divisible by 100, or it is divisible by 400. The is_leap_year function will return True if the year is a leap year and False otherwise.

Is 1992 a leap year, use Python?

Yes, 1992 is a leap year in Python, as well as in the Gregorian calendar. You can use the is_leap_year function mentioned earlier to confirm this:

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

year = 1992
if is_leap_year(year):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")
Code language: Python (python)

When you run this code, it will print: “1992 is a leap year.” This is because 1992 satisfies the conditions for a leap year (divisible by 4 and not divisible by 100).

Read More;

  • Muhammad Nabil

    I am a skilled and experienced Python developer with a huge passion for programming and a keen eye for details. I earned a Bachelor's degree in Computer Engineering in 2019 from the Modern Academy for Engineering and Technology. I am passionate about helping programmers write better Python code, and I am confident that I can make a significant contribution to any team. I am also a creative thinker who can come up with new and innovative ways to improve the efficiency and readability of code. My specialization includes Python, Django, SQL, Apache NiFi, Apache Hadoop, AWS, and Linux (CentOS and Ubuntu). Besides my passion for Python, I am a solo traveler who loves Pink Floyd, online video games, and Italian pizza.

    View all posts

Leave a Comment