Python Modulo

 
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.

Python Modulo Explained (By Example)

The figure shows how the modulo operator works in Python for the example 7%3.

  • 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:

DivisionDivision Without Remainder / Integer DivisionRemainder / MODULO
7/2 == 3.57//2 == 37%2 == 1
8/2 == 4.08//2 == 48%2 == 0
10/3 == 3.3310//3 == 310%3 == 1
14/5 == 2.814//5 == 214%5 == 4

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 i%1000==0.

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:

  1. Two integers
  2. One integer and one float
  3. 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 == operator.

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!

You can learn everything about string formatting in our detailed guide.

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!

Related Video

Arithmetic Operators

Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.

OperatorNameDescriptionExample
+AdditionCalculating the sum of the two operands3 + 4 == 7
SubtractionSubtracting the second operand from the first operand4 - 3 == 1
*MultiplicationMultiplying the first with the second operand3 * 4 == 12
/DivisionDividing the first by the second operand3 / 4 == 0.75
%ModuloCalculating the remainder when dividing the first by the second operand7 % 4 == 3
//Integer Division, Floor DivisionDividing the first operand by the second operand and rounding the result down to the next integer8 // 3 == 2
**ExponentRaising the first operand to the power of the second operand2 ** 3 == 8

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.

Join the free webinar now!