Modulo operator (%) in Python
When we see a ‘%’ the first thing that comes to our mind is the “percent” but in computer language, it means modulo operation(%) which returns the remainder of dividing the left-hand operand by right-hand operand or in layman’s terms it finds the remainder or signed remainder after the division of one number by another.
Given two positive numbers, a and n, a modulo n (a % n, abbreviated as a mod n) is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
The Python Modulo Operator
Basically, the Python modulo operation is used to get the remainder of a division. The modulo operator(%) is considered an arithmetic operation, along with +, –, /, *, **, //. In most languages, both operands of this modulo operator have to be an integer. But Python Modulo is versatile in this case. The operands can be either integers or floats.
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
13 mod 5 = 3
Modulo Operator With float with a negative 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.
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.
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.
Cannot divide by zero! Change the value of the right operand.
Please Login to comment...