Python Modulo Operator

Published on

2 min read

Python Modulo Operator

The modulo operation is an arithmetic operation that finds the remainder of the division of one number by another. The remainder is called the modulus of the operation.

For example, 5 divided by 3 equals 1, with a remainder of 2, and 8 divided by 4 equals 2, with a remainder of 0.

Python Modulo Operator

In Python, the modulo operator is represented by the percent sign (%). The syntax is as follows:

num1 % num2

Here is an example:

5 % 4
1

If the divisor (the second argument) is equal to zero a ZeroDivisionError is raised:

5 % 0
ZeroDivisionError: integer division or modulo by zero

The modulo operator also accepts floating numbers as arguments:

6.8 % 3.4
0.0
When formatting strings, the % character represents the interpolation operator.

Examples

One of the common use cases of the modulo operator is to check whether a number is odd or even. If a number divided by 2 has no remainder, then it is an even number. Otherwise, if it leaves a remainder of 1, then the number is odd:

num = 11

if (num % 2) == 0:
   print(num, "is even")
else:
   print(num, "is odd")

If you run the code above, 11 % 2 leaves a remainder of 1 and the code inside the else statement is executed:

11 is odd

Here is another example, showing how to check if a number is a prime number, using the modulo operator. A prime number is a positive integer that can be divided, without a remainder, only by itself and by 1:

def isPrimeNumber(num):
  if num < 1:
    return False
  for i in range(2, num):
    if (num % i) == 0:
      return False
  else:
    return True

First, we’re checking if the number, num is a positive number. We’re then checking whether the number is divisible by another number in the range from 2 to num without a reminder. If none of the conditions are met, the number is prime.

The modulo operator can also be used to convert units of measure. The following example shows how to convert seconds to minutes:

def secondsToMinutes(sec):
  seconds = sec // 60
  minutes = sec % 60
  return "%d minutes and %d seconds" % (minutes, seconds)

secondsToMinutes(657)
'57 minutes and 10 seconds'

The double slash (//), floor division operator rounds the result to the nearest whole number.

Conclusion

In this article, we have shown you how to use Python’s modulo operator.

If you have any questions or feedback, feel free to leave a comment.