When I studied computer science, the professors pushed us to learn the theory behind modulo operations and residual classes. But many of us lacked motivation. We could not see why calculating the remainder of the division, i.e., modulo, is such an important concept.
Yet, many practical code projects later, I have gained the experience that modulo plays a role in most of them. Modulo is not optional, it’s a critical tool in an expert coder’s toolbelt!
Python Modulo Operator
In Python like in many other programming languages, the modulo operator is represented by the percent
% symbol. It returns the remainder of dividing the left by the right operand. For example, the modulo operation 7%2 returns 1 because seven divided by two is three with remainder 1.
The figure shows how the modulo operator works in Python for the example
- There’s a set with seven elements. This is the dividend of the operation.
- The divisor is 3. You divide the set of seven elements into packages of three elements.
- The remainder is 1. When dividing the set of seven elements into packages of three elements, one remains. This is the result of the modulo operation.
Here are a few examples:
|Division||Division Without Remainder / Integer Division||Remainder / MODULO|
The table shows the result of applying three different operators to two operands:
- The division operator
/that divides the left by the right operand and returns a relatively precise float value.
- The integer division operator
//that divides the left by the right operand and returns the absolute (rounded down) integer value.
- The modulo operator
%that divides the left by the right operand using integer division and returns the remainder of the integer division.
Python Modulo For Loop
Suppose your code has a main loop and you want to execute a monitoring function each thousandth iteration
i. Modulo is your friend here: simply check
for i in range(10**4): if i%1000 == 0: print(i)
The output are all multiples of 1000—that are divisible without remainder:
0 1000 2000 3000 4000 5000 6000 7000 8000 9000
Learning these small code patterns is the key to become a great coder. You must know them by heart, without much thinking. This frees your mental energy and allows you to focus on the big picture. You will produce better and more meaningful code.
Python Modulo Integer and Float
The % modulo operator is used for remainder division on integers. But in Python, you can also apply it to floating point numbers. First, it converts the numeric arguments to a common type—either float or int. Second, it yields the remainder from dividing the first argument by the second.
There are three cases of using integer and floats in a modulo computation:
- Two integers
- One integer and one float
- Two floats
First, calculate the modulo of two integers:
>>> 5%3 2
Second, calculate the modulo of an integer and a float:
>>> 5.5%3 2.5
Third, calculate the modulo of two floats:
>>> 5.5%3.2 2.3
In each case, it divides the first operand by the second and returns the remainder of the division.
Python Modulo If Statement
A frequent use of the modulo operator is within an if condition:
# If Statement + For Loop with Modulo i = 1 for i in range(15): if i%5 == 0: print(i)
Note that the modulo
% operator takes precedence over the
Exercise: Take a guess—what’s the output of this code snippet? You can check it in the interactive code shell:
Python Modulo Negative Numbers
Can you use the modulo operator
% on negative numbers? The answer is yes! Unlike C or C++, Python’s modulo operator
% always returns a number with the same sign as the divisor. For example, -9%2 returns 1 because the divisor is positive, 9%-2 returns -1 because the divisor is negative, and -9%-2 returns -1 because the divisor is negative as well. There’s no “cancelling out” of two negatives.
Here are the two examples:
print(-9%2) print(9%-2) print(-9%-2)
The output has the same sign as the divisor 2 and -2:
1 -1 -1
You can find the reason for the sign of the modulo result on Wikipedia:
However, this still leaves a sign ambiguity if the remainder is nonzero: two possible choices for the remainder occur, one negative and the other positive, and two possible choices for the quotient occur. In number theory, the positive remainder is always chosen, but in computing, programming languages choose depending on the language and the signs of a or n. Standard Pascal and ALGOL 68, for example, give a positive remainder (or 0) even for negative divisors, and some programming languages, such as C90, leave it to the implementation when either of n or a is negative (see the table under § In programming languages for details). a modulo 0 is undefined in most systems, although some do define it as a.
Python Modulo String
The modulo operator % is overloaded by the string class where it means “string formatting” rather than “reminder calculation”. Many coders call this a “string modulo operator”—and it’s available from Python 3.x onward.
name = "FINXTERS!" print('Hello %s' % name) # Hello FINXTERS!
Python Modulo Puzzle
Can you solve this Python puzzle about the modulo operator?
x = 51 % 3 print(x)
You can check whether you’ve correctly figured it out on the Finxter app. Are you a master coder?
Test your skills now!
Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.
|+||Addition||Calculating the sum of the two operands|
|--||Subtraction||Subtracting the second operand from the first operand|
|*||Multiplication||Multiplying the first with the second operand|
|/||Division||Dividing the first by the second operand|
|%||Modulo||Calculating the remainder when dividing the first by the second operand|
|//||Integer Division, Floor Division||Dividing the first operand by the second operand and rounding the result down to the next integer|
|**||Exponent||Raising the first operand to the power of the second operand|
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.