Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
Is there a modulo function in the Python math library?
math
Isn't 15 % 4, 3? But 15 mod 4 is 1, right?
15 % 4
15 mod 4
There's the % sign. It's not just for the remainder, it is the modulo operation.
%
Add a comment
you can also try divmod(x, y) which returns a tuple (x // y, x % y)
divmod(x, y)
(x // y, x % y)
>>> 15 % 4 3 >>>
The modulo gives the remainder after integer division.
mod = a % b
This stores the result of a mod b in the variable mod.
a mod b
mod
And you are right, 15 mod 4 is 3, which is exactly what python returns:
>>> 15 % 4 3
a %= b is also valid.
a %= b
Why don't you use % ?
print 4 % 2 # 0
I don't think you're fully grasping modulo. a % b and a mod b are just two different ways to express modulo. In this case, python uses %. No, 15 mod 4 is not 1, 15 % 4 == 15 mod 4 == 3.
a % b
1
15 % 4 == 15 mod 4 == 3
A = [3, 1, 2, 4] for a in A: print(a % 2)
output:
1 1 0 0
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.