Saturday, April 12, 2014

How to find a leap year in Python!!














How to check leap year in python: Below is python code to find the leap year


def is_leap_year(year):
    """
    below are the conditions for leap year:
    1. divisible by 4
    2. divisible by both 4 and 100
    3. divisible by both 100 and 400
    returns 1 on
    """
    if year%4 == 0:
        if year%100 == 0:
            if year%400 == 0:
                return SUCCESS
            else:
                return FAILED
        else:
            return SUCCESS
    return FAILED

print "Press 0 for exit"
year = input("Enter the year:")
while year:
    if is_leap_year(year):
        print year,"is a leap year"
    else:
        print year,"is not a leap year"
    year = input("Enter the year:")

Output:


Press 0 for exit
Enter the year:2012
2012 is a leap year
Enter the year:1900
1900 is not a leap year
Enter the year:1996
1996 is a leap year
Enter the year:0

You can also use built in python function to find the leap year. Below is the code for that. We need to import calendar module to is isleap() method, which will return True on success and False on fail.

import calendar
print "Press 0 for exit"
year = input("Enter the year:")
while year:
    if calendar.isleap(year):
        print year,"is a leap year"
    else:
        print year,"is not a leap year"
    year = input("Enter the year:")

OutPut:

Press 0 for exit
Enter the year:2012
2012 is a leap year
Enter the year:2014
2014 is not a leap year
Enter the year:1997
1997 is not a leap year
Enter the year:0


Happy Learning!!!

Popular Posts