Skip to content

Python Modulo Operator (%)

  • by

Python Modulo Operator (%) is used to get the remainder of a division problem. With it, you can find the modulus of the given number.

Rem = X % Y   

Python Modulus Operator is an inbuilt operator that returns the remaining numbers by dividing the first number by the second. It is represented as the percentage (%) symbol.

The modulo operator is considered an arithmetic operation, along with +, -, /, *, **, //.

Python modulo operator example

A simple example code gets the remainder of two numbers and checks remainder is even or odd.

for number in range(1, 5):
if number % 2 != 0:
print('Odd:', number)
else:
print('Even:', number)

Output:

Python Modulo Operator (%)

Find the modulus of two float numbers

x = 5.10
y = 1.2

res = x % y
print(x, "%", y, " = ", res)

Output: 5.1 % 1.2 = 0.2999999999999998

ZeroDivisionError exception

This exception happened if the divider operand of the modulo operator becomes zero. That means the right operand can’t be zero.

x = 5
y = 0

try:
res = x % y
print(x, "%", y, " = ", res)
except Exception as ex:
print(ex)

Output: integer division or modulo by zero

Do comment if you have any doubts or suggestions on this operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading