When you see the half of symbol, you’ll think “percent“. But in Python, also as most other programming languages, it means something different.
The % symbol in Python is named the Modulo Operator. It returns the rest of dividing the left operand by right operand. It’s wont to get the rest of a division problem.
The modulo operator is taken into account an mathematical process , along side +, –, /, *, **, //.
The basic syntax is:
In the previous example a is split by b, and therefore the remainder is returned. let’s examine an example with numbers.
The results of the previous example is one. Two goes into seven 3 times and there’s one left over.
The diagram below shows a visible representation of 7 / 2 and 7 % 2 (The “R” stands for “remainder”). the only logo on the proper side (with the green arrow pointing at it) is that the remainder from the division problem. it’s also the solution to 7 % 2 .
Here is another example:
This will end in three. Four doesn’t enter three any times therefore the original three remains left over. The diagram below shows what’s happening. Remember, the modulo operator returns the rest after performing division. the rest is three.
Example using the Modulo Operator
One common use for the Modulo Operator is to seek out even or odd numbers. The code below uses the modulo operator to print all odd numbers between 0 and 10.