Explain Function of Operator in Python



The % symbol in Python is defined as the modulo operator. It can also called as remainder operator. It returns the remainder of the division of two numeric operands (except complex numbers).

The Python modulo % operator is a part of arithmetic operations like addition (+), subtraction (-), multiplication (*), division (/), exponential (**), and floor division (//). The following is the basic syntax for the % modulo operator -

x % y

Modulo Operation on Integers

When we perform a modulo operation on two integers, the result is the remainder of the division, which is also an integer. In the following example, we perform a modulo operation on 23 and 3, i.e., 23 % 3, which results in the integer value 2 -

x = 23
y = 3
p = x % y
print(x, "mod", y, "=", p, sep = " ")

Following is the output of the above code -

23 mod 3 = 2

Modulo Operation on Negative Integers

In Python, when we perform a modulo operation involving negative integers, the result always takes the sign of the divisor (the second operand). For example, -23 % 3 results in 1. This is because Python ensures the result of the modulo is always non-negative when the divisor is positive -

var1=19
var2=2
res1=(-var1)%var2 #divident is negative
res2=var1%(-var2) #divisior is negative
print("The remainder when operand one is negative",res1)
print("The remainder when operand two is negative",res2)

The result is generated as follows -

The remainder when operand one is negative 1
The remainder when operand two is negative -1

ZeroDivisionError

The only exception we will get in the % modulo operator is ZeroDivisionError. This occurs when the divisor (the number after the % symbol) is zero. In the below example, if the divider operand of the modulo operator becomes zero, the right operand can't be zero.

x = 24
y = 0
try:
   print(x, 'mod', y, '=', x % y, sep = " ")
except ZeroDivisionError as err:
   print("It's impossible to divide by zero.")

The result is generated as follows -

It's impossible to divide by zero.
Updated on: 2025-04-18T19:16:17+05:30

554 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements