Skip to content

Effortlessly Mastering Python Modulus Operations

CodeMDD.io

Python Modulo in Practice: How to Use the % Operator

by Jason Van Schooneveld

Modulo in Mathematics

The term modulo comes from a branch of mathematics called modular arithmetic. Modular arithmetic deals with integer arithmetic on a circular number line that has a fixed set of numbers. All arithmetic operations performed on this number line will wrap around when they reach a certain number called the modulus.

A classic example of modulo in modular arithmetic is the twelve-hour clock. A twelve-hour clock has a fixed set of values, from 1 to 12. When counting on a twelve-hour clock, you count up to the modulus 12 and then wrap back to 1. A twelve-hour clock can be classified as “modulo 12,” sometimes shortened to “mod 12.”

The modulo operator is used when you want to compare a number with the modulus and get the equivalent number constrained to the range of the modulus.

For example, say you want to determine what time it would be nine hours after 8:00 a.m. On a twelve-hour clock, you can’t simply add 9 to 8 because you would get 17. You need to take the result, 17, and use mod to get its equivalent value in a twelve-hour context:

8 o'clock + 9 = 17 o'clock
17 mod 12 = 5

17 mod 12 returns 5. This means that nine hours past 8:00 a.m. is 5:00 p.m. You determined this by taking the number 17 and applying it to a mod 12.

Python Modulo Operator Basics

In Python, the modulo operator (%) is used to calculate the remainder of dividing two numbers. It can be used with different numeric types and has a few unique features.

Modulo Operator With int

When using the modulo operator with two integers, it calculates the remainder of the division. For example:

>>> 13 % 5
3

In this case, 13 divided by 5 is 2 with a remainder of 3.

Modulo Operator With float

The modulo operator also works with floating-point numbers. It calculates the remainder of the division, including the fractional part. For example:

>>> 10.5 % 3.2
4.1

In this case, 10.5 divided by 3.2 is 3 with a remainder of 4.1.

Modulo Operator With a Negative Operand

When using the modulo operator with a negative operand, the sign of the result matches the sign of the divisor. For example:

>>> -7 % 3
2

In this case, -7 divided by 3 is -2 with a remainder of 2.

Modulo Operator and divmod()

The divmod() function in Python returns both the quotient and the remainder of dividing two numbers. It can be helpful when you need both values. The divmod() function uses the modulo operator internally. For example:

>>> divmod(20, 7)
(2, 6)

In this case, 20 divided by 7 is 2 with a remainder of 6.

Modulo Operator Precedence

The modulo operator has the same precedence as other arithmetic operators, such as addition and subtraction. It is evaluated from left to right. For example:

>>> 14 + 6 % 5
15

In this case, 6 modulo 5 is 1, and then 14 plus 1 is 15.

Python Modulo Operator in Practice

Now that you understand the basics of the modulo operator, let’s explore some practical examples of how to use it in Python.

How to Check if a Number Is Even or Odd

The modulo operator can be used to determine whether a number is even or odd. When a number is divided by 2, if the remainder is 0, it is even. If the remainder is 1, it is odd. For example:

>>> number = 7
>>> if number % 2 == 0:
... print("Even")
... else:
... print("Odd")
...
Odd

In this case, the number 7 is odd because 7 % 2 returns 1.

How to Run Code at Specific Intervals in a Loop

You can use the modulo operator to run code at specific intervals in a loop. For example, if you have a loop that iterates over a range of numbers, but you only want to run code every 5 iterations, you can use the modulo operator to check for the desired interval. Here’s an example:

>>> for i in range(10):
... if i % 5 == 0:
... print("Code runs every 5 iterations")
...
Code runs every 5 iterations

In this case, the code inside the loop will only run when i % 5 is equal to 0, which happens every 5 iterations.

How to Create Cyclic Iteration

The modulo operator can be used to create cyclic iteration. This means that when you reach the end of a sequence, it wraps around to the beginning. For example:

>>> sequence = ["A", "B", "C"]
>>> index = 5
>>> item = sequence[index % len(sequence)]
>>> print(item)
C

In this case, the sequence has three items. When index is 5, index % len(sequence) is equal to 2, which corresponds to the item “C”.

How to Convert Units

The modulo operator can also be used to convert units. For example, if you have a number of seconds and you want to convert it to hours and minutes, you can use the modulo operator to get the remaining minutes after subtracting the hours. Here’s an example:

>>> total_seconds = 3700
>>> hours = total_seconds https://codemdd.io/ 3600
>>> minutes = (total_seconds % 3600) https://codemdd.io/ 60
>>> print(f"{hours} hours {minutes} minutes")
1 hours 1 minutes

In this case, total_seconds % 3600 returns the remainder of dividing total_seconds by 3600, which is 100. This corresponds to 1 hour and 40 minutes.

How to Determine if a Number Is a Prime Number

The modulo operator can be used to determine if a number is a prime number. A prime number is a number that is only divisible by 1 and itself. For example:

>>> number = 13
>>> is_prime = True
>>> for i in range(2, int(number ** 0.5) + 1):
... if number % i == 0:
... is_prime = False
... break
...
>>> if is_prime:
... print("Prime number")
... else:
... print("Not a prime number")
...
Prime number

In this case, the number 13 is a prime number because it is only divisible by 1 and 13.

How to Implement Ciphers

The modulo operator can be used to implement ciphers, such as the Caesar cipher. A cipher is a method used to encrypt or decrypt messages. The modulo operator is used to wrap the sequence of characters or numbers. Here’s an example of a simple Caesar cipher implementation:

>>> message = "Hello, world!"
>>> key = 3
>>> encrypted_message = ""
>>> for char in message:
... if char.isalpha():
... ascii_offset = ord("A") if char.isupper() else ord("a")
... encrypted_message += chr((ord(char) - ascii_offset + key) % 26 + ascii_offset)
... else:
... encrypted_message += char
...
>>> print(encrypted_message)
Khoor, zruog!

In this case, each character in the message is shifted by the specified key. The modulo operator ensures that the characters wrap around if they exceed the range.

Python Modulo Operator Advanced Uses

In addition to the basic uses of the modulo operator, there are some advanced use cases worth exploring.

Using the Python Modulo Operator With decimal.Decimal

The modulo operator can also be used with the decimal.Decimal class from the decimal module. decimal.Decimal provides support for high-precision decimal arithmetic. The modulo operator works the same way as with other numeric types. For example:

>>> from decimal import Decimal
>>> decimal_number = Decimal("10.5")
>>> divisor = Decimal("3.2")
>>> remainder = decimal_number % divisor
>>> print(remainder)
4.1

In this case, 10.5 % 3.2 returns 4.1 as the remainder of the division.

Using the Python Modulo Operator With Custom Classes

You can override the .__mod__() method in your custom classes to define the behavior of the modulo operator. This allows you to use the modulo operator with instances of your custom class. Here’s an example:

>>> class MyClass:
... def __init__(self, value):
... self.value = value
...
... def __mod__(self, other):
... return self.value % other
...
>>> obj = MyClass(10)
>>> result = obj % 3
>>> print(result)
1

In this case, the .__mod__() method is called when the modulo operator is used with an instance of MyClass. It calculates the remainder of self.value divided by other.

Conclusion

The modulo operator (%) in Python is a useful tool for performing calculations involving remainders. It can be used with different numeric types, and its behavior can be customized in custom classes. Understanding how to use the modulo operator will give you additional flexibility when working with numbers in your Python code.