Leap Year Program In Python Using If Else

A leap year is a year that is divisible by 4, except for years that are both divisible by 100 and not divisible by 400. The leap year is an important concept in various fields, including astronomy, the calendar, and timekeeping. In this article, we will learn how to check leap year in python using if else.

Python Program to Check Leap Year Using if Else

year = int(input("Enter a Year:"))

if(year % 4) == 0:
    if(year % 100) == 0:
        if(year % 400) == 0:
            print("{0} is a leap year". format(year))
        else:
            print("{0} is not a leap year". format(year))
    else:
        print("{0} is a leap year". format(year))
else:
    print("{0} is not a leap year". format(year))

Output:

Enter a Year:2000
2000 is a leap year
Enter a Year:2001
2001 is not a leap year

Code Explanation: Check Leap Year in Python Using if Else

Here we are accepting a year from the user, then converting the same into an integer and we have stored value in a variable year. Next, we have an if statement to check whether a year is divisible by 4  or not; here, we are using the modulus operator for it. If the year is divisible by 4, then we will have another if condition, else we will print year is not a leap year.

In this code, the is leap function takes a year as an input and returns True if the year is a leap year, and False if the year is not a leap year. The year is first checked if it is divisible by 4. If it is, it is then checked if it is divisible by 100. Then checked if it is divisible by 400. If it is divisible by 400, it is a leap year, otherwise, it is not a leap year. If the year is not divisible by 100, it is a leap year.

Let’s run this program. The system will prompt you to enter the year; let’s enter the year 2000. The program will return in 2000 as a leap year. Again run the code and enter the year 2001; the program will print that 2001 is not a leap year.

While the code provided above is a straightforward method for checking if a year is a leap year or not in Python, it may not be the most efficient method. Other methods can be used to check if a year is a leap year or not, including using the calendar module or using mathematical formulas.

In conclusion, leap years play an important role in various fields, and it is important to know how to check if a year is a leap year or not. In this article, we have seen how to write a simple Python program to check if a year is a leap year or not using if else.

If you want to learn python programming, you can refer to this Python Online Course with Certification.

For More Python Programming Exercises and Solutions check out our Python Exercises and Solutions

About The Author