"
This article is part of in the series
Published: Monday 3rd April 2017

We've already covered the modulo (%) operator in a previous lesson, but just as a quick refresher, the modulo is an operator that is used to calculate the remainder of one number divided by another. So if you have an equation such as 6 % 3, the answer would be 0, because 3 goes into 6 evenly, and there is no remainder. The key to understanding the modulo is that it isn't used to calculate the answer to the division of two numbers, but to calculate the remainder. So in the example of 10 % 3, the answer would be 2, because 3 goes into 10 3 times, with a remainder of 2.

A cool way to use the modulo operator is to calculate whether or not a year is a leap year. As you probably know, leap years occur every 4 years, and it's always on years that have multiples of 4, for example, 2000, 2004, 2008, 2012, and 2016 were some of the most recent leap years. Even though leap years are always even years, not every even year is a leap year, because it happens every 4 years rather than every 2. For this reason, the code to check whether a number is even or odd won't work for this particular purpose.

To check if a number is a leap year, we have to see if it is divisible by 4. To do this, we use the modulo to see if a number divided by 4 has a remainder of 0. If it does, then it must be a leap year. If it doesn't, then it can't be one. Check out the code below to see how it works:

year = 2020

if (year % 4) == 0:
 print("{0} is a leap year")
else:
 print("{0} is not a leap year")

This simple code should work with any year you input to determine whether or not it's a leap year. If you try it with 2017, 2018, or 2019, you'll see that neither of those years are leap years. However, if you try it with 2020 like in the example above, you'll find that it is, in fact, a leap year. So the output of the above code is:

2020 is a leap year