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!
3 Answers
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.
2 Comments
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
Modulus (%) operator returns the reminder after division operator.
Example:
5 % 3 = 2 10 % 9 = 1 10 % 9.0 = 1.0
a % breturns the remainder of the division ofabyb. e.g16 % 10would return 6