2.1.3.5 Operators - data manipulation tools

Operators: remainder (modulo)

The next operator is quite a peculiar one, because it has no equivalent among traditional arithmetic operators.
Its graphical representation in Python is the % (percent) sign, which may look a bit confusing.
Try to think of it as of a slash (division operator) accompanied by two funny little 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. 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 the result?
 

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.


  • Console 

Comments

Popular Posts