Given that we are in a leap year this year (2020), it would be nice to know how to programmatically calculate this.
Luckily, this is a repeatable pattern that we can write some code for.
So what is a leap year?
A leap year
is a year that has 29 days in the month of February.
Astronomical years have a quarter of a day more than our calendar years that we follow, so to make sure this matches up continually, our calendar introduces an additional day every 4 years.
Building a pattern
The pattern we can follow to make sure that we write our code correctly is:
If the year is not divisible by 4 then it is a common year Else if the year is not divisible by 100 then it is a leap year Else if the year is not divisible by 400 then it is a common year Else it is a leap year
Writing some code
We can easily turn this into code:
def isLeapYear(year): if year % 4 != 0: return False, "Common year" elif year % 100 != 0: return True, "Leap year" elif year % 400 != 0: return False, "Common year" else: return True, "Leap year"
Our function above takes in a year
variable and returns two variables. A boolean
is it is a leap year or not and a string
telling us what it is.
Testing our code
Let’s test it!
print( isLeapYear(2020) ) # (True, 'Leap year') print( isLeapYear(1999) ) # (False, 'Common year') print( isLeapYear(1685) ) # (False, 'Common year')