Leap year calculator
Introductory tasks
Ask students what a leap year is. When was the last one? When is the next one? Was 1804 a leap year? how about 1900, 2012, 2100? How is a leap year calculated? Get ideas?
The problem
Students have to write a program to return whether or not a year that they give the program is a leap year or not. A leap year can be calculated using the following three-step process:
1) When you divide the year by 4, is there a remainder? If there is a remainder e.g. as for the year 1805, it is not a leap year. If the remainder is zero, you have to go on to step 2.
2) If a number can be divided by 4 without a remainder but not 100 without a remainder, it is a leap year (e.g. 2012). If a number can be divided by both 4 and 100 without a remainder, then you have to go to the last step.
3) If a number can be divided by 4, 100 but not 400 without a remainder, then it is not a leap year (e.g. 1900). If a number can be divided by 4, 100 and 400 without a remainder, then it is a leap year.
This is a really good exercise for students to practice logical problems, Boolean algebra and using functions to return a Boolean value.
Overview of our solution and outline pseudo-code
You can approach this problem in a number of ways. You could ask students to break the problem down themselves first on paper. You could also give students an outline solution that they must use and then let them work out the logic they need e.g.
def is_div4(num):
'''
(int) --> Bool
The function should return True only if the integer can be divided by 4 without a remainder.
'''
def is_div100(num):
'''
(int) --> Bool
The function should return True only if the integer can be divided by 100 without a remainder.
'''
def is_div400(num):
'''
(int) --> Bool
The function should return True only if the integer can be divided by 400 without a remainder.
'''
def is_leapyear(num):
'''
(int) --> Bool
The function should return True only if the integer is a leap year.
'''
#Keep checking leap years until you kill the program.
while True:
print (is_leapyear(int(input('Please enter your year >>> '))))
Solution
Testing
Here is a list of leap years for students to use. These are also available online.
Extension
Students could add some error checking code. They could randomly generate a 4 digit year and test to see if it is a leap year. They could create a file of years (use Excel) and then read each year, testing it for being a leap year. They could either display the years that are leap years and those that aren't, or write the results to two different files, and then display those.