Home » Check if its a Leap Year in Python

Check if its a Leap Year in Python

Oracle Java Certification
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests

In this article we will show you how to create a program in python to check if a year is a leap year.

First of all lets see a definition of a leap year

leap year is a calendar year that contains an additional day added to keep the calendar year synchronized with the astronomical year or seasonal year.

For example, in the Gregorian calendar, each leap year has 366 days instead of 365, by extending February to 29 days rather than the common 28. These extra days occur in each year which is an integer multiple of 4 (except for years evenly divisible by 100, but not by 400).

How to determine whether a year is a leap year

To determine whether a year is a leap year, you can follow these 5 steps:

  1. If the year is evenly divisible by 4 then go to step 2. Otherwise, go to step 5.
  2. If the year is evenly divisible by 100 then go to step 3. Otherwise, go to step 4.
  3. If the year is evenly divisible by 400 then go to step 4. Otherwise, go to step 5.
  4. The year is a leap year
  5. The year is not a leap year

Now lets see an example of how to do this in python

Example

Save the following example as checkleapyear.py, I use thonny

# Default function to implement conditions to check leap year  
def CheckLeapYear(Year):  
  # Check the year is leap year  
  if((Year % 400 == 0) or  
     (Year % 100 != 0) and  
     (Year % 4 == 0)):   
    print("The Year is a leap Year");  
  # it is not a leap year  
  else:  
    print ("The Year is not a leap Year")  

# Get the year from user  
Year = int(input("Enter the year to check: "))

# Print result  
CheckLeapYear(Year)  

Lets see a couple of runs

>>> %Run checkleapyear.py
Enter the year to check: 2000
The Year is a leap Year
>>> %Run checkleapyear.py
Enter the year to check: 1970
The Year is not a leap Year
>>> %Run checkleapyear.py
Enter the year to check: 1700
The Year is not a leap Year
>>> %Run checkleapyear.py
Enter the year to check: 2012
The Year is a leap Year

Link

Here is the code in our github repo

https://github.com/programmershelp/maxpython/blob/main/code%20example/checkleapyear.py

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More