Effortlessly Master Python Modules
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.