Python Program to Find if Given Year is Leap Year or Not

In this article, we will learn about how to write python program to find if given year is a leap year or not. We will see different built-in methods which can be used to do this task.

Getting Started

The task is to find if given year is leap year or not using python program. For example,

If given year is

1900, then output should be “1900 is not a leap year”.
2100, then output should be “2100 is not a leap year”.
2400, then output should be “2400 is a leap year”.

Now, question is “What is a leap year?”

A leap year is a year that is divisible by 4, except for years that are divisible by 100 but not divisible by 400.

So, we will write our program to find if given year is leap or not using above concept.

We can do so in below ways –

  1. Using if-else Condition
  2. Using Calendar Module

Using if-else Condition

We can use simple if-else condition to check if given year is leap or not using python program.

  • Check if given year is divisible by 4 or not.
  • If yes, then check if given year is divisible by 100 or not.
    • If yes, then check if given year is divisible by 400 or not.
      • If yes, then given year is leap year.
      • If no, then given year is NOT a leap year.
    • If no, then given year is a leap year.
  • If no, then given year is NOT a leap year.

Let’s use above concept in python program to find if given year is a leap year or not.

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

# Take input from User
year = int(input("Enter a year: "))

if isLeapYear(year):
    print(year, "is a leap year.")
else:
    print(year, "is not a leap year.")

Here,

  • Inside isLeapYear() method, we check if given year is leap or not.
  • Finally, result is returned and printed using print() function.

Output:

Enter a year: 
2400
2400 is a leap year.

Using calendar Module

We can also use isleap() method present inside calendar module in python to find if given year is leap or not using python program as shown below –

import calendar

year = int(input("Enter a year: "))
result = calendar.isleap(year)

if result:
    print(year, "is a leap year.")
else:
    print(year, "is not a leap year.")

Here,

  • isleap() method present inside calendar module check if given year is leap or not. If yes, it returns True, else False.
  • Finally, result is printed using print() function.

Output:

Enter a year: 
2100
2100 is not a leap year.

Thus, we have see how to write python program to find if given year is leap or not using if-else condition, using isleap() method.

Learn about python at official Doc

Leave a Reply