Reputation: 3505
I have a question about the following statement in Python
if not x % y:
# do something
After seeing this in a piece of code and experimenting I found that if modulo evaluates to anything but zero it'll skip the "do something" code.
My question is, is there a general rule about If and If not statements with implied conditions and are there any good references for Python "tricks" like this?
I apologize about the broad question but this threw me for a loop when I first saw it. I would like to learn as many of these short hand tricks as I can!
Upvotes: 2
Views: 1461
Reputation: 184280
None
is false.0
is false""
is false[]
, ()
, and {}
(and other empty containers) are falseThis can be overridden on your own types by defining __len__()
or __nonzero__()
(the latter is named __bool__()
in Python 3). You could even define, for example, a zero that evaluates as true:
class trueint(int):
def __nonzero__(self):
return True
__bool__ = __nonzero__ # Python 3
truezero = trueint(0)
if truezero:
print("yep, this zero is true!")
You probably shouldn't do this, as it will confuse Python programmers, but you could.
Upvotes: 5
Reputation: 11706
This behaviour is called Truthiness in Python: http://www.udacity.com/wiki/CS258%20Truthiness%20in%20Python
Upvotes: 1
Reputation: 799150
There is no such thing as an "implied condition" in Python; there are true values, and there are false values.
These are false:
None
''
, u''
, b''
, []
, ()
), mappings ({}
), or sets ({,}
)__nonzero__()
methodAnything else should be considered true until proven otherwise.
Upvotes: 2