Javaexercise.com

Program To Find a Leap Year in Python

In this article, we write a python program to find whether a year is a leap year or not. In a leap year, there are 366 days instead of 365 days. A year is a leap year if the following conditions are met:

  1. The year is multiple of 400.

  2. The year is multiple of 4 and not multiple of 100.

Algorithm To Find Leap Year in Python

  1. Input year

  2. if year % 400 == 0 then leap year

  3. else if year % 100 == 0 then not a leap year

  4. else if year % 4 == 0 then leap year

  5. else not a leap year

 

All the programs are executed on the Python3.8 version.

Leap Year Program in Python

This is a simple code for finding a leap year in Python. Here, we checked two major conditions, the first is divisible by 400 and the second is divisible by 4, rest in all the situations, the year will not be a leap year. See the code below.

je_year = int(input("Enter year"))
​
if(je_year % 400 == 0):
    print("leap year")
elif(je_year % 100 == 0):
    print("not a leap year")
elif(je_year% 4 ==0 ):
    print("leap year")
else:
    print("not a leap year")

Output:

Enter year 2021

not a leap year

Output 2:

Enter year 2020

leap year

Leap Year Program in Python - Single line solution

If you are looking for a single-line solution then you can use this code. Here, we just combined all the conditions in a  single statement by using conditional operators. See the example below.

je_year = int(input("Enter year"))
​
if(((je_year % 4 == 0) and (je_year % 100 != 0)) or (je_year % 400 == 0)):
    print("leap year")
else:
    print("not leap year")

Output:

Enter year 1893

not leap year

Leap Year Program using calendar.isleap() method in Python

Python provides a built-in method. We can use python's inbuilt calendar.isleap() method to find whether a year is a leap year or not. This method just takes one argument: the year that needs to be tested. Look at the code below.

import calendar
​
je_year = int(input("Enter year"))
​
if(calendar.isleap(je_year)):
    print("Leap year")
else:
    print("not a leap year")

​Output:

Enter year 2016

Leap year