Skip to content

Effortlessly Master Python Modules

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. The 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, let’s 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 (%) returns the remainder of dividing two numbers.

Modulo Operator With int

When using the modulo operator with integers, the result will always be an integer. The modulo operator simply returns the remainder of the division.

result = 17 % 5
print(result) # Output: 2

In this example, the modulo operator is used to calculate the remainder of 17 divided by 5. The result is 2.

Modulo Operator With float

When using the modulo operator with floating-point numbers, the result will be a floating-point number.

result = 17.5 % 2.5
print(result) # Output: 2.5

In this example, the modulo operator is used to calculate the remainder of 17.5 divided by 2.5. The result is 2.5.

Modulo Operator With a Negative Operand

The behavior of the modulo operator with a negative operand can be surprising. The sign of the result is determined by the sign of the second operand.

result = -17 % 5
print(result) # Output: 3

In this example, -17 is divided by 5, and the remainder is 3. Note that the result is positive because the second operand, 5, is positive.

Modulo Operator and divmod()

The divmod() function in Python can be used to get both the quotient and the remainder of a division.

quotient, remainder = divmod(17, 5)
print(quotient) # Output: 3
print(remainder) # Output: 2

In this example, divmod(17, 5) returns a tuple with the quotient and the remainder.

Modulo Operator Precedence

The modulo operator has the same precedence as the multiplication and division operators. It is evaluated left to right within an expression.

result = 10 + 12 % 5 * 3
print(result) # Output: 16

In this example, the modulo operator has a higher precedence than addition. Therefore, 12 % 5 * 3 is evaluated first, resulting in 6. The overall expression is then 10 + 6, which equals 16.

Python Modulo Operator in Practice

Now that we understand the basics of the modulo operator, let’s explore how it can be used in different scenarios.

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. If a number is divisible by 2 (i.e., the remainder of the number divided by 2 is 0), then it is even. Otherwise, it is odd.

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

In this example, the function is_even() uses the modulo operator to check if a number is even. If the remainder of number divided by 2 is 0, the function returns True, indicating that the number is even.

How to Run Code at Specific Intervals in a Loop

The modulo operator can be useful to execute code at specific intervals within a loop. For example, you may want to perform an action every 10 iterations of a loop.

for i in range(1, 21):
if i % 10 == 0:
print(f"Perform action at iteration {i}")

In this example, the code within the if statement will only be executed when i is a multiple of 10. This allows you to perform a specific action at every 10 iterations of the loop.

How to Create Cyclic Iteration

The modulo operator can also be used to create cyclic iteration. For example, you may want to cycle through a list of items repeatedly.

items = ["apple", "banana", "cherry"]
cycles = 5
for i in range(cycles):
print(items[i % len(items)])

In this example, the modulo operator is used to determine the index of the item in the list based on the current iteration of the loop. By using i % len(items), the index will wrap around to the start of the list when it reaches the end.

How to Convert Units

The modulo operator can be used to convert units of measurement. For example, you may want to convert minutes to hours and minutes.

minutes = 135
hours = minutes https://codemdd.io/ 60
remaining_minutes = minutes % 60
print(f"{minutes} minutes is equal to {hours} hours and {remaining_minutes} minutes")

In this example, the modulo operator is used to calculate the remaining minutes after dividing the total minutes by 60. This allows you to convert minutes to hours and 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. If a number is divisible by any other number (i.e., the remainder of the division is 0), then it is not prime.

def is_prime(number):
if number < 2:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
print(is_prime(11)) # Output: True
print(is_prime(16)) # Output: False

In this example, the function is_prime() checks if a number is divisible by any other number from 2 to the square root of the number. If any of these divisions have a remainder of 0, the number is not prime.

How to Implement Ciphers

The modulo operator can be used to implement ciphers, such as the Caesar cipher. A Caesar cipher is a simple form of encryption that shifts the letters of the alphabet by a certain number of positions.

def caesar_cipher(text, shift):
encrypted_text = ""
for char in text:
if char.isalpha():
if char.islower():
encrypted_char = chr((ord(char) - ord("a") + shift) % 26 + ord("a"))
else:
encrypted_char = chr((ord(char) - ord("A") + shift) % 26 + ord("A"))
encrypted_text += encrypted_char
else:
encrypted_text += char
return encrypted_text
message = "Hello, World!"
shift = 5
encrypted_message = caesar_cipher(message, shift)
print(encrypted_message) # Output: "Mjqqt, Btwqi!"

In this example, the function caesar_cipher() applies the shift value to each letter in the text using the modulo operator. This allows you to encrypt a message using a Caesar cipher.

Python Modulo Operator Advanced Uses

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

Using the Python Modulo Operator With decimal.Decimal

The modulo operator can handle decimal.Decimal numbers as well. When using the modulo operator with decimal.Decimal numbers, the result will be a decimal.Decimal number.

import decimal
value = decimal.Decimal("17.5")
modulo = value % decimal.Decimal("2.5")
print(modulo) # Output: 2.5

In this example, the modulo operator is used with decimal.Decimal numbers to calculate the remainder of value divided by 2.5. The result is a decimal.Decimal number.

Using the Python Modulo Operator With Custom Classes

You can override the .__mod__() method in your custom classes to define how the modulo operator should work with instances of your class.

class CustomNumber:
def __init__(self, value):
self.value = value
def __mod__(self, other):
return f"Custom Number Modulo: {self.value % other}"
number = CustomNumber(17)
modulo = number % 5
print(modulo) # Output: "Custom Number Modulo: 2"

In this example, the .__mod__() method is defined in the CustomNumber class to specify how the modulo operator should handle instances of the class. The result of the modulo operation is a custom string.

Conclusion

The Python modulo operator (%) is a powerful tool for working with numbers. It allows you to calculate remainders, check for even or odd numbers, perform cyclic iteration, convert units, determine prime numbers, implement ciphers, and more.

By understanding the basics of modular arithmetic and the different use cases of the modulo operator, you can leverage this operator to solve real-world problems in your Python code.