How to tell if a year is a Leap Year in Python
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:
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!