Skip to content

Python Math Module: Mastering Numerical Computations

[

Python Modulo in Practice: How to Use the % Operator

by Jason Van Schooneveld basics python

Python supports a wide range of arithmetic operators that you can use when working with numbers in your code. One of these operators is the modulo operator (%), which returns the remainder of dividing two numbers.

In this tutorial, you’ll learn:

  • How modulo works in mathematics
  • How to use the Python modulo operator with different numeric types
  • How Python calculates the results of a modulo operation
  • How to override .__mod__() in your classes to use them with the modulo operator
  • How to use the Python modulo operator to solve real-world problems

The Python modulo operator can sometimes be overlooked. But having a good understanding of this operator will give you an invaluable tool in your Python tool belt.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

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

Now that you understand the concept of modulo in mathematics, let’s dive into the basics of using the Python modulo operator.

Modulo Operator With int

The Python modulo operator works with integers. It takes two integer operands and returns the remainder of dividing the first operand by the second operand.

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

In this example, 17 % 5 returns 2 because 17 divided by 5 equals 3 with a remainder of 2.

Modulo Operator With float

The Python modulo operator can also work with floating-point numbers. However, keep in mind that the result of a modulo operation with floats might not always be accurate due to floating-point precision.

result = 17.5 % 3.2
print(result) # Output: 2.0999999999999996

In this example, 17.5 % 3.2 returns 2.0999999999999996 instead of the expected 2.1. This is a common issue with floating-point arithmetic.

Modulo Operator With a Negative Operand

When one or both of the operands of the modulo operator are negative, the result can be different depending on the Python implementation.

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

In some programming languages, the result of -17 % 5 would be -2. However, in Python, the result is 3. This follows the mathematical definition of modulo where the sign of the result is the same as the sign of the divisor.

Modulo Operator and divmod()

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

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

In this example, divmod(17, 5) returns a tuple containing the quotient 3 and the remainder 2 of dividing 17 by 5.

Modulo Operator Precedence

The modulo operator has precedence in Python expressions. It is evaluated after multiplication, division, and floor division but before addition and subtraction.

result = 2 + 3 * 4 % 5 - 6
print(result) # Output: 1

In this example, 3 * 4 % 5 is evaluated first. The result is 2 because 3 * 4 equals 12, and 12 % 5 equals 2. The expression 2 + 2 - 6 then evaluates to 1.

Python Modulo Operator in Practice

Now that you know the basics of using the Python modulo operator, let’s explore some practical examples of how it can be used.

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 is divisible by 2 without a remainder, it is even. Otherwise, it is odd.

def is_even(n):
return n % 2 == 0
number = 17
if is_even(number):
print(f"{number} is even")
else:
print(f"{number} is odd")

In this example, the function is_even() checks if a number n is even by dividing it by 2 and checking if the remainder is 0. If the remainder is 0, the number is even.

How to Run Code at Specific Intervals in a Loop

The modulo operator can be used to run code at specific intervals within a loop. By using the modulo operator with a loop counter and a desired interval, you can execute code only when the loop counter is a multiple of the interval.

for i in range(1, 11):
if i % 3 == 0:
print(f"Code executed at interval {i}")

In this example, the loop runs from 1 to 10. The code inside the loop prints a message if the loop counter i is divisible by 3. This ensures that the code is executed only at intervals 3, 6, and 9.

How to Create Cyclic Iteration

The modulo operator can be used to create cyclic iteration over a list or a range of values. By using the modulo operator with the length of the list or range, you can loop back to the beginning when reaching the end.

items = ["A", "B", "C"]
for i in range(10):
item = items[i % len(items)]
print(item)

In this example, the loop runs from 0 to 9. The code inside the loop assigns the current item from the list items by using the modulo operator % with the length of the list. This ensures that when the loop counter reaches the end of the list, it wraps back to the beginning.

How to Convert Units

The modulo operator can be used to convert between different units of measurement. By using the modulo operator with a conversion factor, you can determine the remainder and the converted value.

distance_km = 750
conversion_factor_km_mi = 0.621371
distance_mi = distance_km * conversion_factor_km_mi
remainder_mi = distance_km % conversion_factor_km_mi
print(f"{distance_km} kilometers is approximately {distance_mi:.2f} miles with a remainder of {remainder_mi:.2f} miles")

In this example, distance_km represents a distance in kilometers. The code calculates the equivalent distance in miles by multiplying distance_km with the conversion factor conversion_factor_km_mi. It then uses the modulo operator % to determine the remainder in miles.

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. By checking if a number is divisible by any other number, excluding 1 and itself, you can determine if it is a prime number.

def is_prime(n):
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
number = 17
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")

In this example, the function is_prime() checks if a number n is prime. It uses the modulo operator % to check if n is divisible by any number i from 2 to the square root of n. If n is divisible by any of these numbers, it is not a prime number.

How to Implement Ciphers

The modulo operator can be used to implement ciphers, such as the Caesar cipher. A Caesar cipher is a simple substitution cipher that works by shifting the alphabet by a certain number of positions.

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

In this example, the caesar_cipher() function implements a Caesar cipher by shifting each letter in the message string by shift positions. The modulo operator % is used to wrap around the alphabet when shifting.

Python Modulo Operator Advanced Uses

In addition to the basics of using the Python modulo operator, there are advanced use cases that can expand its functionality.

Using the Python Modulo Operator With decimal.Decimal

The Python modulo operator can be used with the decimal.Decimal class from the decimal module, which provides support for arbitrary-precision decimal arithmetic. This allows you to perform modulo operations with decimal numbers accurately.

import decimal
decimal.getcontext().prec = 28
x = decimal.Decimal("17.5")
y = decimal.Decimal("3.2")
result = x % y
print(result) # Output: 2.1

In this example, the decimal module is used to define x and y as decimal.Decimal objects with a high precision. The modulo operation x % y is then performed, and the result 2.1 is returned accurately.

Using the Python Modulo Operator With Custom Classes

The Python modulo operator can be customized by implementing the .__mod__() method in your own classes. This allows you to define the behavior of the modulo operator for objects of your class.

class CustomClass:
def __init__(self, value):
self.value = value
def __mod__(self, other):
if isinstance(other, CustomClass):
return CustomClass(self.value % other.value)
else:
return NotImplemented
x = CustomClass(17)
y = CustomClass(5)
result = x % y
print(result.value) # Output: 2

In this example, the CustomClass implements the .__mod__() method to define the behavior of the modulo operator for objects of the class. This allows you to perform modulo operations between objects of CustomClass.

Conclusion

In this tutorial, you learned the basics of using the Python modulo operator. You explored its usage with different numeric types, its precedence in expressions, and practical examples of how it can be used to solve real-world problems. You also discovered advanced uses of the modulo operator with decimal.Decimal and custom classes. Now you have a strong understanding of the modulo operator’s power and versatility in Python programming. Don’t forget to practice and experiment with the modulo operator to thoroughly grasp its concepts and apply it effectively in your own code.