The Modulus Operator “%” is part of the 3 advanced Arithmetic Operators, together with the Floor Division (//) Operator and Exponent (**) Operator.
The Modulus Operator is used to return an output from the remainder of the division of the left operand, by the right. The Python Modulo Operator is often overlooked, although having a good understanding of this operator will give you an invaluable tool for your Python coding.
There are also 4 basic Arithmetic Operators found in Python, which are used to perform basic mathematical operations including the Addition (+), Subtraction (-), Multiplication (*) and Division (/) operators.
The Arithmetic Operators form part of the other Python Operators collection, which includes the Assignment Operators, Comparison Operators, Logical Operators, Identity Operators, Membership Operators and Bitwise Operators.
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python.
With That said, let’s get started with this Python Modulus Operator Tutorial.
Modulo in Mathematics
To understand how to best use the Modulus Operator in Python, we first need to understand where it originates from in Mathematics.
The term modulo is derived from a branch of mathematics known as Modular Arithmetic.
Modular Arithmetic deals with integer arithmetic on a wrap-around number line that has a fixed set of numbers.
Modular arithmetic works with integer arithmetic, on a circular number line, consisting of a fixed set of numbers. All arithmetic operations performed on this operand will wrap to a certain “modulus” as the operand approaches the number.
Modulo Example: Clock
A very good example of modulo in modular arithmetic is a 12-hour clock, because it has a given set of values, of 1 to 12.
When counting on a 12-hour clock, you count up to modulus 12, before wrapping back to 1, as it cannot exceed higher than that.
It is for this reason that a 12-hour clock is sometimes referred to as “modulo 12,” or shortened to “mod 12”.
You would use the modulo operator when you want to compare a number, with the modulus and get the equivalent number, by constraining it to the range of the modulus.
For example: Let’s say that you want to determine what time it would be 7 hours after 9:00 a.m. On a 12-hour clock, you can’t use the formula of 9 + 7, because if you add 9 to 7, you get 16.
You would correctly need to take the result of 16, and use mod to get its equivalent value in a 12-hour context:
- 9o’clock + 7 hours = 16 o’clock
- 16 mod 12 = 4
16 mod 12 returns a value of 4.
This is because 7 hours past 9:00 a.m. is 4:00 p.m.
We determined this by taking the number 16 and applying it to a mod 12 context.
If you look closer, you will notice that 16 and 4 are equivalent in a mod 12 context. If you were to look at the hour hand at 4:00 and 16:00, it would be in the exact same position.
Modulus Arithmetic Equation
Modular arithmetic uses the following equation to describe this relationship:
- a ≡ b (mod n)
This equation reads as:
- “a and b are congruent modulo n.”
Which is a fancy way of saying that “a and b are equivalent in mod n” because they have the same remainder value, when divided by n.
In other words:
- n is the modulus for both a and b.
If we were to use our clock values of 14 and 4, the equation would look like this:
- 16 ≡ 4 (mod 12)
This now reads as “16 and 4 are congruent modulo 12.” because 16 and 4 have the same remainder value of 4 when divided by 12.
Therefore, in mod 12, the numbers 16 and 4 are equivalent.
We can confirm this using the follow division equations:
- 16 / 12 = 1 R 4
- 4 / 12 = 0 R 5
As both of the operations have the same remainder value of 5, they are equivalent modulo 12.
While this may seem like a lot of math just to understand a Python operator, it is important to grasp this concept first, as it will properly prepare you for using the Modulus Operator in Python.In saying that, let’s now look at the basics of using the Python Modulus Operator together with the numeric types int and float numerical Data Types.
What is the Python Modulus Operator?
The Python Modulus Operator is similar to the other 7 Arithmetic Operators found in Python, as it too can be used with both the numeric types int and float. It can also be used with other types like math.fmod(), decimal.Decimal, as well as your own classes.
How to use the Modulus Operator with an Integer (int) in Python
The Python Modulus Operator will mostly be used with integers (int). When used with two positive integers, it will will return the remainder of standard Euclidean division:
print(19 % 4)
#>> 3
print(17 % 2)
#>> 1
print(591 % 27)
#>> 24
print(10 % 6)
#>> 4
Cannot use Modulus Zero (0)
Just like how you cannot divide by zero with regular division, you cannot use the Python Modulus Operator with a divisor of 0:
print(19 % 0)
#>> ZeroDivisionError: integer division or modulo by zero
How to use the Modulus Operator with a Floating Point (float) in Python
Similar to Integer (int), the Python Modulus Operator can used with a floating point value, which will return the remainder of division, but as a float value instead:
print(14.5 % 3.5)
#>> 0.5
print(87.0 % 17.0)
#>> 2.0
How to use the Modulus Operator with math.fmod() in Python
The math.fmod() can be used to Modulus Operator in Python, as an alternative to using a float with the Modulus Operator:
import math
print(math.fmod(17.5, 5.5))
#>> 1.0
print(math.fmod(9.5, 3.5))
#>> 2.5
The official Python Documentation actually suggests using math.fmod() instead of the Python Modulus Operator when working with float values. This is because of how math.fmod() calculates the result.
Modulus Operator and Rounding off Decimal Values
Similar to the other Python Arithmetic Operators, both the Modulus Operator and math.fmod() may encounter rounding off of decimal values and precision issues when dealing with floating-point arithmetic:
print(17.5 % 5.4)
#>> 1.299999999999999
import math
print(math.fmod(17.5, 5.4))
#>> 1.299999999999999
This is a very important consideration, when maintaining complete floating-point accuracy is vital to your application, such as in banking, where every cent needs to be precise.
The decimal.Decimal module can be used to correct for this.
Modulus Operator with a Negative Operand
You may see different results between math.fmod(x, y) and x % y when using Negative Values.
print(-17.5 % 5.4)
#>> 4.100000000000001
import math
print(math.fmod(-17.5, 5.4))
#>> -1.299999999999999
As you can see the results of these two methods are vastly different.
This happens because of the way computers determine the result of a Modulus Operation, when dealing with a negative operand, as it creates ambiguity as to whether the remainder value should take the sign of the dividend (the number being divided) or the sign of the divisor (the number by which the dividend is being divided by).
Modulus Operator in Different Programming Languages
This becomes even more convoluted when working in different programming languages, as each handles this differently.For example, in JavaScript, the remainder will take the sign of the Dividend:
console.log(13 % -5); //13 is DIVIDEND and -5 is DIVISOR
//>> 3
JavaScript outputs a remainder value of 3 (positive), as it takes the sign of the dividend which is 13.
However, in Python the remainder takes the sign of the Divisor:
print(13 % -5) # 13 is DIVIDEND and -5 is DIVISOR
#>> -2
Python outputs a remainder value of -2 (negative), as it takes the sign of the divisor which is -5.
Different Equations to Calculate Remainder
Beside the difference in Negative and Positive signs, you will also have noticed that the actual values are different between JavaScript and Python as well.
JavaScript had an output remainder of 3 and not -2, while Python had an output of -2 and not -3.
This has to do with how different languages determine the outcome of a modulo operation. Languages such as JavaScript with the remainder that takes the sign of the Dividend use the following equation to determine the remainder:
r = a – (n * trunc(a/n))
In this equation, the three variables are:
- r is the remainder.
- a is the dividend.
- n is the divisor.
The trunc() in this equation stands for truncated division, which will always round a negative number toward zero.
Let’s break it down further to better explain what’s happening:
r = 13 - (-5 * trunc(13/-5))
r = 13 - (-5 * trunc(-2.6)) # 13 ÷ -5 = -2.6
r = 13 - (-5 * -2) # -2.6 Rounded toward 0 = 2
r = 13 - 10 # -5 x -2 = 10
r = 3 # 13 - 10 = 3
As you can see, we get the same remainder output of 3, as we did when we used console.log(13 % -5); in JavaScript.
Languages such as Python with the remainder that takes the sign of the Divisor use the following equation to determine the remainder:
r = a - (n * floor(a/n))
The floor() in this equation stands for floor division, which is actually one of the seven Arithmetic Operators in Python.
Floor Division will return the same results as Truncated Division, except with that when a negative number is used, floor division will round the result down, away from zero instead:
r = 13 - (-5 * floor(13/-5))
r = 13 - (-5 * floor(-2.6)) # 13 ÷ -5 = -2.6
r = 13 - (-5 * -3) # -2.6 Rounded away from 0 = -3
r = 13 - 15 # -5 x -3 = 15
r = -2 # 13 - 15 = -2
As you can see, we get the same remainder output of -2, as we did when we used print(13 % -5) in Python.
With all this said and explained, you are probably wondering why this matters if you only use Python?
Well, it’s important to understand because not all Modulus Operations in Python are the same. When using modulus with the int and float Data Types, it will take the sign of the Divisor, however, with other Data Types such as math.fmod() it will not.
print(13.0 % -5)
#>> -2.0
import math
print(math.fmod(13.0, -5.0))
#>> 3.0
Just like in JavaScript, math.fmod() takes on the sign of the dividend, which uses Truncated Division, whereas float uses the sign of the divisor.
Other Python Data Types such as decimal.Decimal also use Truncated Division.
How to use Modulus Operator with divmod() Function
Python has a built-in function called divmod(), which internally uses the Modulus Operator.
The divmod() Function takes two parameters and returns a Python Tuple that contains the results of Floor division and modulo using the supplied parameters.
Below is an example of using divmod() with 42 and 8:
print(divmod(42, 8)) #divmod() Function
#>> (5, 2) # Tuple
print(42 // 8) # Floor Division
#>> 5
print(42 % 8) # Modulus
#>> 2
Here we can see that divmod(42, 8) returns the Python Tuple (5, 2).
- The 5 is the result of the Floor Division of 42 and 8
- The 2 is the result of 42 Modulus 8.
How to use divmod() Function with a Negative number
Let’s now see what happens when the second parameter is a negative number when using the divmod() Function.
Remember that when the Python Modulus Operator is used with an Integer (int), the remainder will take the sign of the Divisor which in this case is -9:
print(divmod(42, -9)) #divmod() Function
#>> (-5, -3)
print(42 // -9) # Floor Division
#>> -5
print(42 % -9) # Modulus
#>> -3 # Result takes on the sign of Divisor being -9
The result of -3 takes on the sign of Divisor being -9.
Modulus Operator Precedence
As with the other Python Operators, there are rules that determine the Modulus Operator’s precedence when evaluating expressions.
The Modulus Operator (%) has the same level of precedence, as when compared to the Multiplication Operator (*), Division Operator (/) and Floor Division Operator (//).
Take a look at an example of the modulo operator’s precedence below:
print(6 * 12 % 4 - 3)
#>> -3
As both the Multiplication Operator and Modulus Operator have the same level of precedence, Python will evaluate them from left to right.
If were were to break down this into 3 separate steps, it would look as follows:
print(6 * 12)
#>> 72
print(72 % 4)
#>> 0
print(0 - 3)
#>> -3
We can see that we in fact get the same output result of -3.Much like in regular algebra mathematics, we can use Parenthesis ( ) to change the order in which the equation is calculated.
print(6 * 12 % (4 - 3))
#>> 0
By adding the parenthesis, we are now telling Python to first calculate (7 – 3) = 4. It then calculates 6 x12 = 72, then calculate 72 % 4 as follows:
print(7 - 3)
#>> 4
print(6 * 12)
#>> 72
print(72 % 4)
#>> 0
We again see that the output result is the same value of 0, as with the print(6 * 12 % (4 – 3)) statement. This result is however different compared to when we didn’t use the extra Parenthesis ( ) earlier, which gave us an output of -3 instead.
Conclusion
I hope you enjoyed this tutorial on how to create and use a Python Modulus Operator. This should give you the starting knowledge you need to easily implement it into you next Python code or project
Python Modulus Operator Summary
Here is a summary of what we learnt when using the Modulus Operator in Python:
- How modulo works in mathematics using a clock as an example
- How to use the Python Modulus Operator with both the int and float numeric Data Types
- Modulus cannot be used with Zero
- How Python calculates the results of a Modulus Operation and how its different to JavaScript
- How to use the Modulus Operator with math.fmod()
- How to use the Modulus Operator with divmod() Function
- How Modulus Operator Precedence works
Real World usage of the Modulus Python Operator
Now that you better understand how the Modulus Operator works, it’s time to take your knowledge one step further as we explore ways in which you would actually use the Python Modulus Operator, in order to solve real world programming problems.
Share the love
If you enjoyed this tutorial content and would like others to benefit from it as well, make sure to share it on your favorite Social Media platform, using the share buttons below.
Subscribe for News & Discount Offers
Subscribe right now to gain instant access to the latest news and tutorials while also being the first to know about, exclusive offers and discounts!