Skip to content

Learn How to Effortlessly Use the mod in Python

CodeMDD.io

Python Modulo in Practice: How to Use the % Operator

Table of Contents:

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

The Python modulo operator (%) returns the remainder of dividing two numbers. It can be applied to different numeric types, such as int and float.

Modulo Operator With int

When using the modulo operator with int values, it returns the remainder of the division. Here’s an example:

>>> 5 % 2
1

The result of 5 % 2 is 1, because when 5 is divided by 2, the remainder is 1.

Modulo Operator With float

When using the modulo operator with float values, the fractional part of the number is ignored. Here’s an example:

>>> 5.5 % 2
1.5

The result of 5.5 % 2 is 1.5, because when 5.5 is divided by 2, the remainder is 1.5.

Modulo Operator With a Negative Operand

The modulo operator in Python handles negative operands differently than some other programming languages. The result takes the sign of the second operand. Here’s an example:

>>> -5 % 3
1

The result of -5 % 3 is 1, because the modulo operator takes the sign of the second operand (3), and the remainder of -5 when divided by 3 is 1.

Modulo Operator and divmod()

In addition to using the modulo operator directly, you can also use the divmod() function to get both the quotient and the remainder of a division operation. The divmod() function returns a tuple with the quotient and the remainder. Here’s an example:

>>> divmod(10, 3)
(3, 1)

The result of divmod(10, 3) is (3, 1), where 3 is the quotient and 1 is the remainder when 10 is divided by 3.

Modulo Operator Precedence

The modulo operator has higher precedence than the addition, subtraction, and multiplication operators in Python. This means that the modulo operator is evaluated before other arithmetic operations. Here’s an example:

>>> 10 + 5 % 3
12

The result of 10 + 5 % 3 is 12, because the modulo operator (5 % 3) is evaluated first, resulting in 2, and then the addition operator adds 10 and 2 to give 12.

Python Modulo Operator in Practice

Now that you have an understanding of the basics of the modulo operator in Python, let’s see how it can be used in practice to solve various problems.

How to Check if a Number Is Even or Odd

The modulo operator is commonly used to check if a number is even or odd. If a number modulo 2 is 0, then it is even. Otherwise, it is odd. Here’s an example:

def is_even(number):
return number % 2 == 0
print(is_even(4)) # Output: True
print(is_even(5)) # Output: False

In this example, the function is_even() takes a number as input and returns True if the number is even, and False otherwise. The modulo operator is used to check if the number modulo 2 is 0, which is the condition for an even number.

How to Run Code at Specific Intervals in a Loop

Another use case for the modulo operator is to run code at specific intervals within a loop. The modulo operator can be used to check if a certain number of iterations have been completed. Here’s an example:

for i in range(10):
if i % 2 == 0:
print("Running code at even iteration:", i)
else:
print("Running code at odd iteration:", i)

In this example, the code runs a loop from 0 to 9. The modulo operator is used to check if the current iteration number (i) is even or odd. If it is even, a specific code block is executed. If it is odd, a different code block is executed.

How to Create Cyclic Iteration

The modulo operator can also be used to create cyclic iteration. This means that when a certain value is reached, the iterator wraps around and starts again from the beginning. Here’s an example:

fruits = ["apple", "banana", "cherry", "date", "elderberry"]
index = 0
for _ in range(10):
print(fruits[index % len(fruits)])
index += 1

In this example, the code prints the elements of the fruits list in a cyclic manner. The modulo operator is used to ensure that the index variable wraps around to 0 when it reaches the length of the fruits list. This creates a cyclic iteration through the list.

How to Convert Units

The modulo operator can be used to convert units by constraining a value to a specific range. For example, let’s say you want to convert a value from meters to centimeters, but you want to keep the result within the range of 0 to 100. You can use the modulo operator to accomplish this. Here’s an example:

def meters_to_centimeters(meters):
centimeters = meters * 100
return centimeters % 100
print(meters_to_centimeters(1.5)) # Output: 50

In this example, the meters_to_centimeters() function takes a value in meters and converts it to centimeters. The modulo operator is then used to ensure that the result is within the range of 0 to 100. The result is the remainder after dividing the centimeters by 100.

How to Determine if a Number Is a Prime Number

The modulo operator is commonly used in algorithms to determine if a number is a prime number. A prime number is a number that is only divisible by 1 and itself. Here’s an example:

def is_prime(number):
if number < 2:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
print(is_prime(17)) # Output: True
print(is_prime(18)) # Output: False

In this example, the is_prime() function takes a number as input and checks if it is divisible by any number from 2 to number - 1. If the modulo operation for any of these numbers is 0, it means that the number is not prime and the function returns False. If the loop completes without finding any divisors, the number is prime and the function returns True.

How to Implement Ciphers

Ciphers are algorithms used for encryption and decryption. The modulo operator is often used in the implementation of ciphers to wrap around the alphabet or the range of characters being encrypted. Here’s a simple example of a Caesar cipher implementation:

def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
ascii_offset = 65 if char.isupper() else 97
shifted = (ord(char) - ascii_offset + shift) % 26 + ascii_offset
result += chr(shifted)
else:
result += char
return result
encrypted_text = caesar_cipher("Hello, World!", 3)
print(encrypted_text) # Output: Khoor, Zruog!

In this example, the caesar_cipher() function takes a text and a shift value as input and encrypts the text using a Caesar cipher. The modulo operator is used to wrap around the alphabet when shifting the characters.

Python Modulo Operator Advanced Uses

The Python modulo operator can be used with other numeric types and even with custom classes.

Using the Python Modulo Operator With decimal.Decimal

The decimal module in Python provides a Decimal class for precise decimal arithmetic. The modulo operator can be used with Decimal values in the same way as with other numeric types. Here’s an example:

from decimal import Decimal
value = Decimal("10.5")
modulus = Decimal("3")
result = value % modulus
print(result) # Output: 1.5

In this example, the Decimal values 10.5 and 3 are used with the modulo operator. The result is 1.5, which is the remainder after dividing 10.5 by 3.

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 for instances of your class. Here’s an example:

class Circle:
def __init__(self, radius):
self.radius = radius
def __mod__(self, other):
if isinstance(other, Circle):
return self.radius % other.radius
raise NotImplementedError
circle1 = Circle(5)
circle2 = Circle(3)
result = circle2 % circle1
print(result) # Output: 3

In this example, the Circle class represents a circle with a radius. The .__mod__() method is implemented to calculate the modulo of the radii of two Circle instances. The result is 3, which is the remainder after dividing 5 by 3.

Conclusion

In this tutorial, you learned how to use the Python modulo operator (%) to calculate remainders. You also explored various use cases for the modulo operator, such as checking if a number is even or odd, running code at specific intervals, creating cyclic iteration, converting units, determining prime numbers, and implementing ciphers.

CodeMDD.io