Reputation: 192
I saw such a use of the modulo operator in a lambda function testing for primality. Can someone explain why the following statement will execute as long as i is greater than x if this isn't to my knowledge an actual boolean statement. It works with division as well if the numerator is greater than the denominator regardless if they are factors or not.
if x % i:
# Execute random foolishness
NOTE: I have only tried this in Python and Java so if this works in another language I apologize as it is probably not a language specific question.
Upvotes: 4
Views: 7155
Reputation: 107297
For digit objects python assumes every non-zero value as True
and zero as False, thus the condition if x % i:
will be True until x
is not divisible by i
, else it would be False
.
>>> bool(-1)
True
>>> bool(3)
True
>>> bool(0)
False
There is also such criteria for other objects like lists or strings, if you have a empty list or string python will evaluate it as False and for other cases it would be True.
>>> bool(0)
False
>>> bool([])
False
>>> bool('')
False
>>> bool('a')
True
>>> bool([1])
True
>>> bool([''])
True
Actually it's Truth value testing :
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a
__bool__()
or__len__()
method, when that method returns the integer zero or bool value False.All other values are considered true — so objects of many types are always true.
Upvotes: 2
Reputation: 50570
The statement is a condensed for form of:
if x % i != 0
As long as the modulo is not zero, this if
will execute. If a number is evenly divisible by i
, it will not perform the if
block.
Upvotes: 0
Reputation: 8561
Python treats non-zero values as True, so if x % i:
is the same as if x % i != 0:
. It's just a quick way to test if x
is evenly divisible by i
.
Upvotes: 4