PYTHON

The Python Modulo Operator – What Does the % Symbol Mean in Python?

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:

a % b

In the previous example a is split by b, and therefore the remainder is returned. let’s examine an example with numbers.

7 % 2

 

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:

3 % 4

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.

for number in range(1, 10):
    if(number % 2 != 0):
        print(number)

Result:

1
3
5
7
9
READ  Indentation in Python with Examples

About the author

Wikitechy Editor

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X