Python Modulo

Python modulo operation is done using %, the modulus operator.

>>> 5 % 2
1
>>> 20 % 6
2

The Python modulo operation returns the remainder after whole number division of the arguments. In the example above 20/6 is 3 and 2 left over. The 2 left over is what the modulo operation returns.

Dividing by a smaller number:

>>> 3 % 4
3

Using the modulus operator on a float:

>>> 5.5 % 4
1.5

That’s because 5.5 = 4 * 1 + 1.5.

If any of the numbers in the operation are floats, Python will return a float.

Doing the modulus operation with zero as the divisor will throw a ZeroDivisionError

>>> 3 % 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

When to use the modulo operation

Fizz Buzz is a famous coding problem popularized on coddinghorror.com in 2007. The article talked about how the majority of software developer candidates couldn’t solve a simple interview question. The central operation of the coding problem was the modulo operation.

The coding problem says that you have to loop from 1 to 100, replacing every number divisible by 3 with “Fizz”, every number divisible by 5 with “Buzz”, and every number divisible by both 3 and 5 with “FizzBuzz”. To figure out when a number is divisible by another number, we will use the modulus operator.

if i % 3 == 0:
    print(f'We know that {i} is divisible by 3')

That’s a pretty good use of the modulo operation in programming.