Python Language Simple Mathematical Operators Modulus


Example

Like in many other languages, Python uses the % operator for calculating modulus.

3 % 4     # 3
10 % 2    # 0
6 % 4     # 2

Or by using the operator module:

import operator

operator.mod(3 , 4)     # 3
operator.mod(10 , 2)    # 0
operator.mod(6 , 4)     # 2

You can also use negative numbers.

-9 % 7     # 5
9 % -7     # -5
-9 % -7    # -2

If you need to find the result of integer division and modulus, you can use the divmod function as a shortcut:

quotient, remainder = divmod(9, 4)
# quotient = 2, remainder = 1 as 4 * 2 + 1 == 9