Python Modulo – % Operator, math.fmod() Examples

Python modulo operator (%) is used to get the remainder of a division. The modulo operation is supported for integers and floating point numbers.

The syntax of modulo operator is a % b. Here “a” is dividend and “b” is the divisor. The output is the remainder when a is divided by b.

If both “a” and “b” are integers, then the remainder is also an integer. If one of them is float, the result is also a floating point number.


Python Module Operator Example

Let’s look at some examples of modulo operator.

1. Modulo with integers

>>> 10 % 3 
1
>>> 2 % 2
0
>>> 

2. Modulo with float

>>> 9 % 3.0
0.0
>>> 10 % 3.0
1.0
>>> 

3. Modulo with user inputs

x = input("Please enter first number:\n")
fx = float(x)

y = input("Please enter first number:\n")
fy = float(y)

print(f'{x} % {y} = {fx % fy}')
Python Modulo Operator
Python Modulo Operator

When we get the user entered data, it’s in the form of string. We are using the float() built-in function to convert them to floating point number. That’s why the remainder is 1.0 and not 1.

Recommended Read: Python input() function


4. ZeroDivisionError Example

If the divisor is 0, the modulo operator will throw ZeroDivisionError. We can use try-except block to catch the error.

a = 10.5
b = 0

try:
    print(f'{a} % {b} = {a % b}')
except ZeroDivisionError as zde:
    print("We cannot divide by 0")
Python Modulo ZeroDivisionError
Python Modulo ZeroDivisionError

5. Modulo with Negative Numbers

Python modulo operator always return the remainder having the same sign as the divisor. This can lead to some confusion with the output.

>>> -5 % 3
1
>>> 5 % -3
-1
>>> -10 % 3
2
>>> 
  • -5 % 3 = (1 -2*3) % 3 = 1
  • 5 % -3 = (-1 * -2*-3) % 3 = -1
  • -10 % 3 = (2 -4*3) % 3 = 2

6. Python Modulo math.fmod()

The behavior of % operator with negative numbers is different from the platform C library. If you want the modulo operation to behave like C programming, you should use math module fmod() function. This is the recommended function for getting modulo with floating point numbers.

>>> import math
>>> math.fmod(-5, 3)
-2.0
>>> math.fmod(5, -3)
2.0
>>> math.fmod(-10, 3)
-1.0
>>> 
  • fmod(-5, 3) = fmod(-2 -1*3, 3) = -2.0
  • fmod(5, -3) = fmod(2 -1*-3, -3) = 2.0
  • fmod(-10, 3) = fmod(-1 -3*3, 3) = -1.0

Overloading Modulo Operator

We can overload modulo operator by implementing __mod__() function in our class definition.

class Data:

    def __init__(self, i):
        self.id = i

    def __mod__(self, other):
        print('modulo function called')
        return self.id % other.id

    def __str__(self):
        return f'Data[{self.id}]'


d1 = Data(10)
d2 = Data(3)

print(f'{d1} % {d2} = {d1%d2}')

Output:

modulo function called
Data[10] % Data[3] = 1

Quick word on Floating Point Arithmetic Issues

We use binary format to store values in computers. When it comes to fractions, most of the times we can’t represent them exactly as binary fractions. For example, 1/3 can’t be represented in exact binary format and it will always be an approximate value.

That’s why you can get unexpected results when performing arithmetic operations with floating point numbers. It’s clear from the output of below modulo operations.

>>> 9.6 % 3.2
3.1999999999999993

The output should be 0 because 3.2*3 is 9.6. But, the float fraction values are not exactly represented and the approximation is causing this error. It’s clear from this example too.

>>> 9.6 == 3.2 * 3
False
>>> 

So, you should give extra care when working with floating point numbers. It’s advisable to perform a rounding and then only compare two floating point numbers.

>>> round(9.6, 3) == round(3.2 * 3, 3)
True

References: