Python modulo operator

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:

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!

Leave a Reply

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}