1

I am new to programming, and I chose to learn Python, and I came across this operator (%) called modulus, but I don't understand it, can some explain it to me in more detail!

1
  • 1
    a % b returns the remainder of the division of a by b. e.g 16 % 10 would return 6 Commented May 9, 2019 at 19:35

3 Answers 3

2

It is used to calculate the remainder of an integer division, like 5 % 3 which yields 2. It returns the remainder for all numeric operands on the left-hand-side (that is, if the first operands is an integer, fraction, float, Decimal numbers.

But it is also used after strings to interpolate data into the string, using a legacy markup from C's printf - like in :

"Hello %s. Your age is %d" % ("Daniel", "23") 

Which yields:

'Hello Daniel. Your age is 23' 

In this use, % is used as an operator after the string. The % ocurrences inside the string are the markup to indicate placeholders for an objetct to be rendered as a string, and an object to be rendered as an integer number. The parameters to be rendered are on the tuple, on the right-hand-side of the operator.

This mode works for strings (str) or bytes objects. And last, but not least, in Python all operators are overloadable, depending on the class of the objects being used as operands - so you might as well find % doing other things - all that is needed is that the class of the objects being operated implement the __mod__ or __rmod__ methods.

Sign up to request clarification or add additional context in comments.

2 Comments

Python does modulo: you are describing remainder. They are not the same thing for negative arguments.
"The % (modulo) operator yields the remainder from the division of the first argument by the second." docs.python.org/3/reference/expressions.html - maybe you'd better file a bug report against the language docs.
1

Modulus Operator (%) returns the remainder of the division.

For Example:

  • 5 % 3 = 2
  • 4 % 2 = 0
  • 3 % 5 = 3
  • 10.5 % 3 = 1.5

1 Comment

Python does modulo: you are describing remainder. They are not the same thing for negative arguments.
0

Modulus (%) operator returns the reminder after division operator.

Example:

5 % 3 = 2 10 % 9 = 1 10 % 9.0 = 1.0 

1 Comment

Python does modulo: you are describing remainder. They are not the same thing for negative arguments.