# A python function which takes in a year (2000, 1963, 2001, etc.) and returns True if the year is a leap year, # or False if the year is a common year # # http://stackoverflow.com/questions/3220163/how-to-find-leap-year-programatically-in-c has an interesting discussion # about leap year algorithms # # http://pythonfiddle.com/is-leap-year-redux by Peter Shank def is_leap_year(year): # years not divisible by 4 (1601, 1999, etc) are common years if year%4 != 0: return False # years that ARE divisibible by 4 but are NOT divisible by 100 (1604, 2012, etc) are leap years elif year%100 != 0: return True # years divisible by both 4 and 100, but NOT divisible by 400 (1700, 1900, etc) are common years elif year%400 != 0: return False # years failing the three tests are divisible by 400 (1600, 2000, etc.) and they are leap years else: return True def test(): test_cases = [(1600, True), (1601, False), (1602, False), (1603, False), (1604, True), (1700, False), (2000, True), (2012, True)] passes = 0 for (args, answer) in test_cases: result = is_leap_year(args) if result != answer: print "Failed when argument was: ", args else: passes = passes + 1 print str(passes) + " out of " + str(len(test_cases)) + " cases passed." test()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question