In Python, the modulo operation can be performed using the %
operator.
remainder = dividend % divisor
This operator returns the remainder of the division of one number by another. The syntax for the modulo operation is:
remainder = dividend % divisor
Here's a simple example:
a = 10
b = 3
remainder = a % b
print(remainder) # Output will be 1
In this case, 10 % 3
equals 1
because 10 divided by 3 is 3 with a remainder of 1.
number = 10
if number % 2 == 0:
print("Even")
else:
print("Odd")
days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
day_index = 10 % 7
print(days_of_week[day_index]) # Output will be "Wednesday"
for i in range(1, 21):
if i % 5 == 0:
print(f"{i} is a multiple of 5")
Here are some additional points about the modulo operation:
-10 % 3 # Output will be 2
10 % -3 # Output will be -2
5.5 % 1.5 # Output will be 0.5
ZeroDivisionError
:>>> 5 % 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
%
operator is efficient and can handle very large numbers since Python supports arbitrary-precision integers.Understanding modulo can be particularly useful for solving problems related to cyclic phenomena, patterns, or conditional evaluations across a finite set of possibilities.