user
How to do the modulo operator in Python?
alphonsio

How to do the modulo operator in Python?

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.

Use Cases for Modulo Operator

  1. Checking Even or Odd Numbers:
number = 10
if number % 2 == 0:
    print("Even")
else:
    print("Odd")
  1. Cycling Through Values:
days_of_week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
day_index = 10 % 7
print(days_of_week[day_index])  # Output will be "Wednesday"
  1. Looping with Step:
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:

  • The modulo operator can also work with negative numbers.
-10 % 3  # Output will be 2
10 % -3  # Output will be -2
  • For floating-point numbers:
5.5 % 1.5  # Output will be 0.5

Edge Cases

  1. Divisor is Zero:
    Attempting to use zero as the divisor will raise a ZeroDivisionError:
>>> 5 % 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
  1. Handling Large Numbers:
    The % 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.