The Modulo Operator in Python

The modulo operator is used in Python programming when you need to find the remainder of integer division. It comes up in many important algorithms, and is represented by the symbol %. The % operator gives the result of dividing the number on the left of the symbol by the number on the right and keeping the remainder.

For example:

for i in range(1, 11):
    print("10 % {} = {}".format(i, 10 % i))

Output:

10 % 1 = 0
10 % 2 = 0
10 % 3 = 1
10 % 4 = 2
10 % 5 = 0
10 % 6 = 4
10 % 7 = 3
10 % 8 = 2
10 % 9 = 1
10 % 10 = 0

Check these divisions for yourself and make sure you understand why the results are what they are.

Even and Odd in Python

One very common use of the modulo operator is to determine whether an integer is even or odd. Have a think about how you might do this yourself before revealing the code below. Hint: One way to think of oddness and evenness of integers is to consider what happens when you divide them by two.

There are many other applications for the modulo operator in Python programming. Particularly in Cryptography. One very common use is in the classic software developer interview question Fizz Buzz:

Fizz Buzz is a game for two or more players. Take it in turns to count aloud from 1 to 50, but each time you are going to say a multiple of 3, replace it with the word “Fizz”. For multiples of 5, say “Buzz” and for numbers which are multiples of both 3 and 5, say “Fizz Buzz”.

Have a go at coding this for yourself before looking a the solution below. You don’t need to worry about there being two players. Just loop through the numbers from 1-50 and output “Fizz”, “Buzz” or “Fizz Buzz” as required.

Python Solution for the Classic Fizz Buzz Interview Problem

So there you have it. The modulo operator in Python. Definitely one to add to your Python programming toolkit!

Happy Computing!

Sharing is caring!

1 Comment on “The Modulo Operator in Python

Leave a Reply

Your email address will not be published. Required fields are marked *