Modulo Operator in Python

What is the result of % in Python?

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

Taken from http://docs.python.org/reference/expressions.html

Example 1:
6%2 evaluates to 0 because there's no remainder if 6 is divided by 2 ( 3 times ).

Example 2: 7%2 evaluates to 1 because there's a remainder of 1 when 7 is divided by 2 ( 3 times ).

So to summarise that, it returns the remainder of a division operation, or 0 if there is no remainder. So 6%2 means find the remainder of 6 divided by 2.

Python Modulo Operator without An Equal Sign and A Not-Equal Sign

The expression number % 2, where number is even, will give you zero. That's a falsey value in Python, hence the if will fail and it will output Even. It's no different to:

>>> if 0:
... print('zero')
... else:
... print('nonzero')
...
nonzero

If you wanted the if statement to succeed for an even number, you would be better off using number % 2 == 0, which will give you True for even numbers. That equivalent statement would be written as:

return 'Even' if number % 2 == 0 else 'Odd'

However, given your constraints in the title (no == or !=), that's not allowed(a). The use of "reversed" logic gets around this problem.


By the way, other methods to do this could include (amongst probably a great many more):

return 'Even' if not number % 2 else 'Odd'
return ['Even', 'Odd'][number % 2]

(a) Though I rather dislike artificial limitations of this type educators often slip into assignments. After all, when will a developer really be called upon to implement something without the = key? Maybe if their keyboard is broken? But then, your bigger issue is surely working for a company that won't shell out $5 for a new keyboard :-)

Why is the modulo operator used in this function?

The modulus operator returns the remainder of a division. You can learn more about here.

In your context, this means it keeps the index within the circular array to avoid the index going out of bounds.

For example, if you have an array that has a length of 4, but your next index is 6, this code % len(arr) changes the 6 to become 2 because 6 % 4 = 2. So it means, it wraps the index around to the start of the array.

If your next index is 2, since 2 is less than 4, this operation % len(arr) will result in the remainder, which is 2. So the index remains unchanged if it's within the bounds of the array.

I hope that helps!



Related Topics



Leave a reply



Submit