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!
Noneis false.0is 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:You probably shouldn’t do this, as it will confuse Python programmers, but you could.