🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeMod in Python: Modulo and math.fmod

When you need the remainder from a division in Python, you can use the % operator or math.fmod(). Modulo gives you the remainder paired with division, and those two options differ in how they handle signs.
This article shows how to calculate a remainder and choose the operation that fits your calculation.
TL;DR
Use % for Python’s floor-division remainder, and use math.fmod() when you need the dividend-signed remainder convention.
- For positive operands, 10 % 3 returns 1.
- Python’s % result follows the divisor’s sign, while math.fmod() follows the dividend’s sign.
- A zero divisor raises ZeroDivisionError, and floating-point results can show representation error.
What Is Modulo in Python?
Modulo gives the remainder paired with division. In Python, the expression a % b uses floor division, so a == (a // b) * b + (a % b) for numeric values where the operation is defined.
The left operand a is the dividend and the right operand b is the divisor. For 10 % 3, floor division gives 3 and the remainder is 1 because 10 equals 3 times 3 plus 1.
For a positive divisor, the result stays in the range from zero up to, but not including, that divisor. This makes modulo useful for a bounded bucket or slot number. For example, item_number % 4 maps consecutive item numbers to four repeating slots, starting over at zero after each group.
The quotient and remainder can be unpacked from divmod() when a task needs both values. For a minutes count, the first value is whole hours and the second is leftover minutes.
This identity also helps debug a result: multiply the quotient by the divisor, then add the remainder. The sum should recover the dividend. With negative values, use Python’s // result in that check rather than truncating the quotient toward zero.
Negative divisors can be valid, but their result range follows their sign. If an algorithm expects a zero-based array index, a negative divisor is usually the wrong choice even though Python accepts it. Keeping the cycle length positive makes the resulting positions predictable.
How to Use Modulo in Python Step by Step
The percent operator works directly in an expression, while math.fmod() provides a second remainder convention for floating-point work. I ran python3 modulo_demo.py and got the following output:
Step 1: Calculate a basic remainder
Put the dividend, percent sign and nonzero divisor in one expression. This small example shows both a remainder and a division with no remainder.
print(10 % 3)
print(12 % 3)
Output:
1
0
The result is zero when the dividend is evenly divisible. For the tutorial run, I checked the same rule alongside negative operands and fmod:
10 % 3 = 1
-5 % 3 = 1
-5 // 3 = -2
math.fmod(-5, 3) = -2.0
8.0 % -3.0 = -1.0
math.fmod(8.0, -3.0) = 2.0
9.6 % 3.2 = 3.1999999999999993
Here, the two functions differ when signs matter, and the last line shows a float approximation rather than an exact decimal remainder.
Step 2: Choose % or math.fmod()
Choose the operation by the sign convention your calculation needs. Python’s % stays aligned with floor division and the divisor’s sign, which suits cyclic indices and calendar-style wraparound.
import math
print(-5 % 3)
print(math.fmod(-5, 3))
print(8.0 % -3.0)
print(math.fmod(8.0, -3.0))
Output:
1
-2.0
-1.0
2.0
math.fmod() follows the dividend sign, like truncation-based remainder in C. The official Python math documentation generally prefers fmod for floating-point operands, while % remains the natural choice for integer modulo and nonnegative cycles. Read more about Python’s / and // operators to see how the quotient relates to the remainder.
Step 3: Use modulo in a small task
To check parity, divide by two and inspect whether the remainder is zero. The same test can run on an integer variable in a conditional statement.
number = 14
if number % 2 == 0:
print("even")
else:
print("odd")
Output:
even
Modulo can schedule an action every few iterations without storing a separate counter. When the loop index is divisible by the interval, the remainder is zero, so the condition runs at the selected positions.
for step in range(8):
if step % 3 == 0:
print(step)
Output:
0
3
6
The loop starts at zero, so the first match occurs immediately. If an action should happen only after a completed interval, test (step + 1) % 3 == 0 instead, which shifts the matches to iterations three and six.
A cyclic sequence uses a related rule: new_index = (index + movement) % length. With a positive length, this folds forward or backward movement into the valid range. A negative movement can wrap to the final item, which is why a positive divisor is a useful convention for list positions.
Do not use the same expression when you need the signed distance left after division. For example, a geometry calculation may need the remainder to stay negative when its input is negative. In that case, test whether math.fmod() matches the domain’s definition rather than assuming the two operations are interchangeable.
Python Modulo Edge Cases and Choices
A modulo result depends on the divisor, the operand signs and the numeric type. Check which case matches your input before choosing a fix.
| Case | What happens | What to do |
|---|---|---|
| Divisor equals zero | ZeroDivisionError is raised | Validate the divisor or catch the exception |
| Negative operand with % | Result follows divisor sign | Use that rule with floor division |
| Negative operand with math.fmod() | Result follows dividend sign | Choose it for truncation-style remainder |
| Float values such as 9.6 and 3.2 | Binary representation can affect result | Use Decimal for decimal quantities or compare with a tolerance |
Handle zero before calculating
A divisor of zero makes remainder undefined, so Python raises an exception instead of returning a number. The failure message from the integer probe was ZeroDivisionError: integer modulo by zero.
divisor = 0
if divisor == 0:
print("Choose a nonzero divisor")
else:
print(10 % divisor)
Validate data before the expression when zero is an expected input. A try-except block is appropriate when an operation can fail after validation or when input arrives from another function.
For text entered by a user, convert it to a number before applying modulo and handle invalid text separately. The Python operators guide covers the wider operator family. When text represents a decimal quantity, construct Decimal from the text rather than first converting it to float.
Account for floating-point precision
Python float values use binary floating-point, and many decimal fractions have no exact binary representation. Therefore 9.6 % 3.2 can produce 3.1999999999999993 instead of the decimal-looking zero a reader might expect.
from decimal import Decimal
print(Decimal("9.6") % Decimal("3.2"))
Output:
0.0
Construct Decimal from strings when decimal digits are the source of truth, such as entered monetary values. Rounding a float before comparison can hide an error and should only be used when the required precision is known.
To see both quotient and remainder together, call divmod(a, b). It returns the same quotient-and-remainder pair as a // b and a % b, which can make the relationship clear in code.
print(divmod(-5, 3))
Output:
(-2, 1)
Conclusion
Python’s % returns a remainder paired with floor division, while math.fmod() follows a dividend-signed convention. Pick the one that matches the calculation, guard against a zero divisor, and avoid exact comparisons between binary floats.
For the official details, see Python’s arithmetic expression reference and math.fmod() documentation. The floating-point tutorial explains why decimal-looking values may be approximate.
FAQ
These quick answers address common questions about modulo syntax, negative results and function choices.
How do you do mod in Python?
Use the percent operator: a % b returns the remainder paired with floor division, provided b is not zero.
Why is -5 % 3 equal to 1 in Python?
Python rounds -5 // 3 down to -2, and -5 equals (-2 * 3) + 1. The remainder follows the divisor’s sign.
Should I use % or math.fmod() for floats?
Choose based on the sign convention you need. Python’s math documentation generally prefers math.fmod() for floats, while % follows the divisor sign and pairs with floor division.
What happens when the divisor is zero?
Python raises ZeroDivisionError. Check the divisor or catch the exception before relying on a remainder.


