Módulo 17 de 24 · Texto
Operators: remainder (modulo)
Operators: remainder (modulo)
The next operator is quote a peculiar one, because it has no equivalent among traditional arithmetic operators.
Its graphical representation is Python is the % (percent) sign, which may look a bit confusing.
Try to think of it as a slash (division operator) accompanied by two funny circles.
The result of the operator is a remainder left after the integer division.
In other words, it's the value left over after dividing one value by another to produce an integer quotient.
Note: the operator is sometimes called modulo in other programming languages.
Take a look at the snippet - try to predict its result and then run it:
print(14%4)
As you can see, the result is two.
2
This is why:
- 14//4 gives 3 -> this is the integer quotient
- 3*4 gives 12 -> as a result of quotient and divisor multiplication
- 14-12 gives 2 -> this is the remainder
This example is somewhat more complicated:
print(12 % 4.5)
What is ther result?
3.0 - not 3 but 3.0 (the rule still works: 12 // 4.5 gives 2.0; 2.0 * 4.5 gives 9.0; 12 - 9.0 gives 3.0)
Operators: how not to divide
As you probably know, division by zero doesn't work.
Do not try to;
- perform a division by zero
- perform an integer division by zero
- find a remainder of a division by zero