What Does a Modulo Operator (%) Do in Python?
The modulo operator (%) in Python returns the remainder of a division and is one of the most widely used arithmetic operators in programming. It powers everyday tasks like checking divisibility, wrapping array indices, converting between number bases, and implementing algorithms for GCD, primality testing, and modular arithmetic used in cryptography and number theory.
Key takeaways
- Sign follows the divisor: Python's
%operator always returns a remainder with the same sign as the divisor, which differs from C, C++, and JavaScript where the sign follows the dividend. - Modulo identity guarantee: For any
q, r = divmod(n, d), Python guarantees thatq * d + r == n, making it safe to reason about results regardless of operand signs. - Decimal type behaves differently: When using Python's
Decimalobjects, the%operator bases the sign of the result on the numerator instead of the denominator, so extra caution is needed. - Common practical uses: The operator handles even/odd checks, clock-style value wrapping, digit extraction, base conversion, hashing, and loop iteration gating with minimal code.
- Alternatives in the math module:
math.fmod()follows the dividend's sign (like C), andmath.remainder()returns the IEEE 754-style nearest remainder, so choosing the right function matters for scientific or geometric applications.
Let’s start with an enumerated illustration. A company wants to use the minimum number of requests for an online service. They also want to complete the work in parallel mode to minimize the total time without wasting any processor in an idle state.
When they use two parallel requests they find that in the last round only one processor is busy, which means the other one is idle. They decide to use three processors and distribute the number of requests evenly…to their surprise, they again still find one processor in the last round while the other two are idle. They use four processors the next time, then five, six…again to the result that only one processor is busy in the last round, all others are wasted. They finally use seven processors and all work equally, without any wasted cycle.
So, what can we learn about the least number of requests here?
Let’s dive right in!
Learn to Code: Python for Absolute Beginners
The tools that help create a document, a movie, or a game are all programs. This course uses Python as its programming language. Python programmers are in high demand. The programs you’ll learn in this course are specially designed for learners with no programming background. You’ll start with simple math, real-world problem-solving, and writing solutions as steps in a simple language. Next, you’ll learn decision-based solutions demonstrated via flowcharts and explained with execution sheets. Finally, you’ll learn to translate your solutions into Python programs using variables, conditional statements, loops, strings, lists, and built-in functions. You’ll also learn to create your own functions in Python. Plenty of practice programs with the facility of editing and running them in an embedded way will add to your confidence. After completing this course, you can start as a Python developer. Python is used in business, web, healthcare, education, data science, scraping, embedded systems, and games.
Introduction#
You might have heard of the coin distribution problem, which is very similar to the one narrated in the abstract. Let’s review it briefly:
When distributing number of coins among two, three, four, five, or six people, one coin is left over. But when distributed among seven people, they are distributed equally. Similarly, in the problem of the parallel processor mentioned above, the number of requests are completely divisible by only seven; one request remains in the last round when there are two, three, four, five, or six of them.
The following conditional expressions can correctly test the value of n:
(
(
(n % 2) == (n % 3) ==
(n % 4) == (n % 5) ==
(n % 6) == 1
)
and (n % 7) == 0
)
What does the modulo % operator mean? This is the modulus operator that divides the left-hand side by the right-hand side and returns the remainder (not the quotient). We need to test the natural numbers until we reach the value of n such that the above condition is true. We can reduce iterations through the least common multiple of 2, 3, 4, 5, and 6. Let’s stick to the topic, not the example.
One of the most common examples of modulus is the time on the clock. It keeps rounding to the smallest value whenever it crosses its largest value. For example, after 59 the minutes and seconds are rounded to 0. Similarly, the value of hours becomes 0 after 23 (for a 24-hours clock) and 1 after 12 (in a 12-hours clock). To implement the same logic for minutes and seconds in Python, we can do the following:
var = var + 1
if (var == 60): var = 0
var = var + 1
var = var % 60
Similarly, we can implement the logic for the hours part depending upon the type of clock (12-hour or 24-hour).
Modulus is a valuable operation in computer science.
Zero to Hero in Python
Python is powering the global job market and is one of the leading programming languages today because of its high scalability and ease of use. If you don't have a programming background, this Skill Path is the perfect place for you to start learning about Python. In this Skill Path, you will learn about real-world problem-solving techniques and how to write step-by-step solutions in English and Python. You will start by covering the basic syntax and functionality of Python to create basic programs. In the latter half of this Skill Path, you will get a detailed overview of object-oriented programming to create scalable, modular, and cleaner code. Moreover, you will get hands-on experience practicing with commonly used algorithms and data structures. By the end of this Skill Path, you will build a Rock, Paper, and Scissors game and its desktop app using the Tkinter library in Python to enhance your programming skills and kickstart your career as a Python developer.
Practical uses of % for beginners#
Talking to new Python programmers, the following are the common uses of the modulus operator:
-
Whether a number is even or odd:
number % 2returns a non-zero value (True) ifnumberis odd. -
Check if is divisible by :
N % Mreturns0ifNis divisible byM. -
Check if is a multiple of :
N % Mreturns0ifNis a multiple byM. -
Get the last digits of a number :
N % (10 ** M) -
Wrapping values (for array indices):
index = index % len(array)restrictsindexto remain between0andlen(array) - 1, both inclusive. -
Forcing a number to a certain multiple:
tens = value - (value % 10) -
Put a cap on a particular value:
hour % 24returns a number between0and23. -
Bitwise operations:
x % 256is the same value asx & 255. -
Commonly used in hashing:
h(k) = k % mmaps a keykinto one of thembuckets.
Programs using the % operator#
The following basic programs are examples of other common uses of the modulus operator:
-
Returning a fraction instead of a decimal-point result of a division:
# frac (7, 3) returns (2,1,3) # frac (6, 3) returns (2,0,3) # frac (6,0) returns (None,0,0) def frac(n, d): if d==0: return (None, 0, d) return (n//d, n%d, d) -
Converting an elapsed time (given in seconds) into hours, minutes, and seconds:
# time (5000) returns (1,23,20) # time (500) returns (0,8,20) # time (50) returns (0,0,50) def time(s): ss = s % 60 s //= 60 mm = s % 60 s //= 60 hh = s % 24 return (hh, mm, ss) -
The progress is only reported every time through the loop (to do something every iteration as opposed to doing on every iteration):
# loop (70) prints 0,10,20,30,40,50,60,69 # loop (30) prints 0,10,29,29 # loop (15) prints 0,10,14 def loop(s): for i in range(s): if i%10 == 0: print(i,end=',') print(i) -
Reversing the digits in a number.
# rev (1579) returns 9751 # rev (234) returns 432 # rev (60) returns 6 def rev(n): r = 0 while n>0: d = n % 10 r = r * 10 + d n //= 10 return r -
Converting an integer in base 10 (decimal) to another base:
# octa (255) returns 377 # octa (63) returns 77 # octa (7) returns 7 def octa(n): b = 8 t = 1 r = 0 while n>0: d = n % b r = t * d + r t = t * 10 n //= 8 return r -
Converting a linear array to a matrix structure:
# a1to2 ([10,20,30,40]) returns [[10, 20], [30, 40]] # a1to2 ([10,20,30,40,50]) returns [[10, 20], [30, 40], [50, 0]] # a1to2 ([10,20,30,40,50,60,70,80]) returns [[10, 20], [30, 40], [50, 60], [70, 80]] def a1to2(a1): s = len(a1) cols = int(s ** 0.5) rows = s // cols if rows*cols < s: rows = rows+1 print(rows,cols) a2 = [[0 for i in range(cols)] for j in range(rows)] for i in range(s): r = i // cols c = i % cols a2[r][c] = a1[i] return a2 -
Computing the greatest common divisor:
# gcd (12340,236) returns 4 # gcd (10,20) returns 10 # gcd (20,10) returns 10 def gcd(a,b): if (a>b): x,y = a,b else: x,y=b,a while y!=0: r = x % y x = y y = r return x -
Computing the least common multiple:
# lcm (20,30) returns 60 # lcm (15,20) returns 60 # lcm (30,7) returns 210 def lcm(a,b): if (a>b): x,y = a,b else: x,y=b,a l = y while l % x > 0: l = l + y return l -
Testing if a number is prime or composite:
# is_prime (20) returns False # is_prime (19) returns True # is_prime (21) returns False def is_prime(n): if n<2: return False r = int(n**0.5)+1 for i in range(2,r): if n % i == 0: return False return True;
Modular arithmetic is used in number theory, group theory, and cryptography.
Grokking Coding Interview Patterns in Python
I created Grokking the Coding Interview because I watched too many talented engineers fail interviews they should have passed. At Microsoft and Meta, I saw firsthand what separated the candidates who succeeded from the ones who didn't. It wasn't how many LeetCode problems they'd solved. It was whether they could look at an unfamiliar problem and know how to approach it the right way. That's what this course teaches. Rather than throwing hundreds of disconnected problems at you, we organize the entire coding interview around 28 fundamental patterns. Each pattern is a reusable strategy. Once you understand two pointers, for example, you can apply them to dozens of problems you've never seen before. The course walks you through each pattern step by step, starting with the intuition behind it, then building through increasingly complex applications. As with every course on Educative, you will practice in a hands-on way with 500+ challenges, 17 mock interviews, and detailed explanations for every solution. The course is available in Python, Java, JavaScript, Go, C++, and C#, so you can prep in the language you'll actually use in your interview. Whether you're preparing for your first FAANG loop or brushing up after a few years away from interviewing, this course will give you a repeatable framework for cracking the coding interview.
Peculiarities of % operator in Python#
Mathematically, it is always guaranteed that
if
q, r = divmod(n, d),
then
q * d + r == n.
The divmod() receives a number n and divisor d as parameters and returns a quotient q and a remainder r as results. The sign of the remainder depends on the sign of the divisor:
- A positive divisor results in a positive remainder.
- A negative divisor results in a negative remainder.
The following table shows a comparison of positive and negative divisors in Python, along with the reasoning.
| Consider | 21 % 4 is 1 | 21 % -4 is -3 |
|---|---|---|
| Because | 21 // 4 == 5 | 21 // -4 == -6 |
| Compare | 5 * 4 + 1 == 21 | (-6) * (-4) + (-3) == 21 |
Behavior of % for int vs. Decimal#
So what does the modulo ‘%’ operator do for decimal type objects? In Python, the result of the % operator for Decimal type objects is different from the result of the % operator for simple integers.
The sign of the numerator is used with the result when the
Decimalobject is used as the operand. Otherwise, the sign of the denominator is used.
In the above code, we have demonstrated the change in the remainder due to the change in the sign of the denominator. The first group of statements uses the % operator while the other uses the divmod() function to show the quotient for clarity of the remainder value.
In the above code, the result carries the sign of the numerator used in the expression. The remainder value results from simple (unsigned) values of operands without following the rule q * d + r == n.
Be cautious when using the
Decimalobjects with the%operator in Python. The result is different from that of simple integers.
Understanding the sign rule and the modulo identity#
One of the most common mistakes beginners make is misunderstanding how Python’s modulo operator behaves with negative numbers. Unlike some other languages, Python’s % operator ensures that the result always has the same sign as the divisor.
For example:
print(-5 % 4) # 3print(5 % -4) # -3print(-5 % -4) # -1
This might look confusing at first, but Python guarantees the following identity:
x == (x // y) * y + (x % y)
This identity holds true for all integer and floating-point modulo operations. Understanding it helps you reason about the result — no matter the signs of the operands.
Using divmod() for cleaner code#
In many cases, you might need both the quotient and the remainder from a division. Instead of calling // and % separately, Python offers the built-in divmod() function, which returns both in one step:
q, r = divmod(-17, 5)print(q) # -4print(r) # 3
This is equivalent to writing:
q = -17 // 5r = -17 % 5
…but it’s cleaner and often more efficient. This makes divmod() a great choice when you care about both results at once — for example, in number theory problems, pagination logic, or custom hashing functions.
Modulo with floats (and what isn’t supported)#
The % operator works with floats just like it does with integers:
print(7.5 % 2.5) # 0.0print(-7.5 % 2.5) # 0.0
It still follows the same identity and sign rules. However, keep in mind:
Using
%with complex numbers is not supported and will raise aTypeError.If you need to perform modulo operations on complex values, you’ll need to implement them manually.
% vs math.fmod() vs math.remainder()#
Python’s % isn’t the only way to compute a remainder. The math module provides two alternatives — and they behave slightly differently.
import mathprint(-7 % 4) # 1 (sign of divisor)print(math.fmod(-7, 4)) # -3 (sign of dividend)print(math.remainder(7, 4)) # -1 (IEEE 754 remainder)
Here’s how they differ:
| Sign of divisor |
| Most Pythonic choice |
| Sign of dividend |
| Scientific computing, geometry |
| IEEE 754 rule |
| Signal processing, DSP |
Understanding these differences is crucial when you’re working with low-level math, geometry, or scientific applications.
Behavior differences from other programming languages#
If you’re coming from C, C++, or JavaScript, you might notice that Python’s % behaves differently. Many other languages define the remainder based on the dividend’s sign, but Python bases it on the divisor’s.
// C / JavaScriptprintf("%d", -5 % 4); // -1
# Pythonprint(-5 % 4) # 3
This difference is intentional — it makes % behave consistently with the // operator and the modulo identity. If you’re porting code from another language, be mindful of this distinction.
Using modulo with NumPy arrays#
If you’re working with scientific or data-heavy applications, you’ll likely use NumPy. The good news: % behaves the same way on arrays.
import numpy as npa = np.array([-7, 7])b = np.array([4, 4])print(np.remainder(a, b)) # [1 3]print(np.fmod(a, b)) # [-3 3]
np.remainder()and the%operator behave like Python’s built-in modulo (sign of divisor).np.fmod()behaves likemath.fmod()(sign of dividend).
This distinction becomes especially important in signal processing, data science, and numerical simulations.
Edge cases and errors to know#
There are a few common pitfalls you should be aware of when using the modulo operator:
Division by zero:
x % 0raises aZeroDivisionError.Custom types: If you define a class with
__mod__,%can be overloaded.String formatting:
%is also used in old-style string formatting — e.g.,"Hello %s" % name.
Although still supported, f-strings (f"Hello {name}") are preferred today.
Understanding these edge cases helps you write safer, more predictable code.
Wrapping up and next steps#
The modulus operator in Python is represented with the % operator. There are other built-in functions like divmod() that can be used to compute the remainder as a result of division. For simple integers, Python guarantees q * d + r == n for q, r = divmod(n, d). The result of the % operator differs if the operands are the objects of the Decimal type.
Happy learning!
To start learning these concepts and more, check out Educative’s Zero to Hero in Python skill path.