Leap Year in Python

Year 2008 is a leap year. The leap year thing is always interesting. Sometimes I also think about the unfortunate people who have birthday on 29th February! :)

Let me write two modules that determines whether a year is leap year or not, (I also write test module for this).



def is_leap_year2(year):
    if year % 400 == 0:
        return True
    elif year % 100 == 0:
        return False
    elif year % 4 == 0:
        return True
    else:
    return False

def is_leap_year(year):
    if year % 100 != 0 and year % 4 == 0:
        return True
    elif year % 100 == 0 and year % 400 == 0:
        return True
    else:
        return False

def test_is_leap_year():
    years = [1900, 2000, 2001, 2002, 2020, 2008, 2010]

    for year in years:
        if is_leap_year2(year):
            print year, "is leap year"
        else:
            print year, "is not a leap year"

#program starts from here
test_is_leap_year()


After writing the code I found a nice discussion in python google group. Click here.

You can also take a look at the wikipedia article on leap year.

Comments

حسن said…
how about just ```calendar.isleap( 2008 ) ```
:)
AshGavs said…
This comment has been removed by the author.
AshGavs said…
This comment has been removed by the author.
GZ said…
I would test year%4 first.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code