"
This article is part of in the series
Last Updated: Thursday 23rd February 2017

It's pretty easy to use Python to perform calculations and arithmetic. One cool type of arithmetic that Python can perform is to calculate the remainder of one number divided by another. To do this, you need to use the modulo operator (otherwise known as the percentage sign: %). When you place a modulo in between two numbers, it calculates the remainder of the first number divided by the second number. If the second number goes into the first evenly, then there is no remainder and the calculated answer is 0. If the second number doesn't go into the first evenly, then you'll have some sort of number returned as the answer.

Take a look at the following equations to see how it works:

6 % 3
10 % 3

In the first example, 3 goes into 6 evenly (exactly 2 times), so the answer to the equation is 0. In the second example, 3 does not go into ten evenly. It goes into 10 three times, with the remainder of 1. Remember, you're not trying to find the answer to ten divided by three -- the modulo is used to find the remainder of that equation. which is 2. So the answers to the above equations are 0 and 2, respectively.

A great way to use the modulo in context is to use it to test whether for odd or even numbers. If a number can be divisible by 2 without a remainder, then by definition the number is even. If the number is divided by 2 that equation yields a remainder, then the number must be odd. To put this concept into Python terms, see the code snippet below:

if (num % 2 == 0): #number is even -- insert code to execute here
else: #number is odd -- insert code to execute here

The code above basically states that if a the remainder of a number divided by 2 is equal to zero, the number is even. If not, the number is odd. This snippet can be used to execute a number of different functions based on whether or not the number in question is even or odd -- insert your functions where it says "insert code here" to add some functionality to the snippet.