0

Alternative use of % in Python:

I'm a newbie programmer learning Python. My understanding of the use of the % operator is that it returns the remainder of a division operation. However, I was looking at a piece of code to calculate whether a number in a list is prime, and I ran across a use of this operator that I didn't understand. def is_prime_number(x): if x >= 2: for y in range(2,x): if not ( x % y ): return False else: return False return True In the fourth line, the % operator seems to be returning a boolean result rather than an integer. For the code to work, I think it would have to mean "if x is divisible by y," so x % y would mean "x is not divisible by y." I set up a test to confirm this. if 4 % 2: print("% means 'is divisible by'") else: print("% means 'is not divisible by'") #output: % means 'is not divisible by' I can't seem to find an explanation of this usage in any searches about the Python operators. Any insight as to why this works as it does would be much appreciated.

26th Jun 2019, 1:58 AM
Luos
Luos - avatar
2 Réponses
+ 4
The modulus operator (%) does return the remainder of a division. Just remember that 0 is interpreted as False and any other number as True. When "x" is divisible by "y" the remainder of their division is 0 (False). print(bool(4 % 2)) # False On the other hand, when "x" is not divisible by "y" the remainder of their division is any positive number (True). print(bool(3 % 2)) # True
26th Jun 2019, 2:30 AM
Diego
Diego - avatar
+ 1
if not x%y: is the exact same as if x%y == 0: because if x is divisible by y, it would be 0, the boolean equivalent of false. so,”if 4%2” is false. “not” keyword reverses that.
26th Jun 2019, 2:33 AM
Choe
Choe - avatar