The Python Oracle

How to calculate a mod b in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2

--

Chapters
00:00 Question
00:22 Accepted answer (Score 260)
00:37 Answer 2 (Score 60)
00:53 Answer 3 (Score 43)
01:07 Answer 4 (Score 27)
01:32 Thank you

--

Full question
https://stackoverflow.com/questions/9910...

Answer 1 links:
[divmod(x, y)]: https://docs.python.org/3/library/functi...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 263


There's the % sign. It's not just for the remainder, it is the modulo operation.




ANSWER 2

Score 43


>>> 15 % 4
3
>>>

The modulo gives the remainder after integer division.




ANSWER 3

Score 28


mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4
3

a %= b is also valid.




ANSWER 4

Score 11


Why don't you use % ?


print 4 % 2 # 0