Modulo operator (%) in Python (original) (raw)
Last Updated : 17 Feb, 2025
Modulo operator (%) in Python gives the remainder when one number is divided by another. Python allows both integers and floats as operands, unlike some other languages. It follows the Euclidean division rule, meaning the remainder always has the same sign as the divisor. It is used in finding even/odd numbers, cyclic patterns, and leap year calculations. The divmod(a, b) function can also be used to
Example of Modulo operator (%):
10 % 4 gives 2 because 10 divided by 4 leaves a remainder of 2.
Python `
rem=10%4 print(rem)
`
Table of Content
- Syntax of Modulo operator
- Modulo Operator with Integer
- Modulo Operator with negative float number.
- Example using the Modulo Operator
- ZeroDivisionError in Python
**Syntax of Modulo operator
a ****%** b
Here, a is divided by b, and the remainder of that division is returned.
Modulo Operator with Integer
Stores the remainder obtained when dividing a by b, in c
Python `
inputs
a = 13 b = 5
c = a % b print(a, "mod", b, "=", c, sep=" ")
`
**Output:
13 mod 5 = 3
Modulo Operator with negative float number.
Stores the remainder obtained when dividing d by e, in f. For more examples, refer to How to Perform Modulo with Negative Values in Python.
Python `
inputs
d = 15.0 e = -7.0
f = d % e print(d, "mod", e, "=", f, sep=" ")
`
**Output:
15.0 mod -7.0 = -6.0
**Example using the Modulo Operator
Suppose, we want to calculate the remainder of every number from 1 to n when divided by a fixed number k.
Python `
function is defined for finding out
the remainder of every number from 1 to n
def findRemainder(n, k):
for i in range(1, n + 1):
# rem will store the remainder
# when i is divided by k.
rem = i % k
print(i, "mod", k, "=",
rem, sep=" ")
Driver code
if name == "main":
# inputs
n = 5
k = 3
# function calling
findRemainder(n, k)
`
**Output:
1 mod 3 = 1 2 mod 3 = 2 3 mod 3 = 0 4 mod 3 = 1 5 mod 3 = 2
ZeroDivisionError in Python
The only Exception you get with the Python modulo operation is **ZeroDivisionError. This happens if the divider operand of the modulo operator becomes **zero. That means the **right operand can’t be zero. Let’s see the following code to know about this Python exception.
Python `
inputs
a = 14 b = 0
exception handling
try: print(a, 'mod', b, '=', a % b, sep=" ")
except ZeroDivisionError as err: print('Cannot divide by zero!' + 'Change the value of the right operand.')
`
**Output:
Cannot divide by zero! Change the value of the right operand.