A leap year is a year that contains 366 days in a year instead of 365. It contains an additional day to keep the calendar year synchronized with the astronomical year. In the Gregorian calendar, a leap year occurs every four years, except for years that are divisible by 100 but not by 400. In this article, we will discuss how to write a Python program to check whether a given year is a leap year or not.
The condition to become a year leap are:
- The year must be evenly divisible by 4.
- If the year is divisible by 100, then it must also be divisible by 400.
For Example:
2000 and 2004 is a leap year as it is divided by 4.
There are various ways to write Python programs to check whether a given year is a leap year or not.
Method 1: Check Leap Year Using if else in Python
year = int(input("Please Enter a year: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
else:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Output
Enter a year: 2000
2000 is a leap year
Method 2: Check Leap Year Using ternary operator Python
year = int(input("Please Enter a year: "))
leap_year = "Leap year" if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else "Not a leap year"
print(leap_year)
Output
Please Enter a year: 2004
Leap year
Method 3: Using Calendar module of Python
import calendar
year = int(input("Please Enter a year: "))
leap_year = "Leap year" if calendar.isleap(year) else "Not a leap year"
print(leap_year)
Output
Please Enter a year: 2010
Not a leap year