if a
checks if a
1 is truthy. More specifically, it checks the return value of a.__bool__()
. With int
s, this effectively looks like this:
# explaining is easier with python's syntax
if myInt == 0:
myInt.__bool__() returns False
else:
myInt.__bool__() returns True
Note that in the above example, I was not providing actual python code. As @jwodder points out, the post should say myInt.__nonzero__
in python2 (I hope the point is not lost on you despite the lack of specific correctness, though).
It is also the case that NoneType.__bool__()
always returns False.
Now, onto the second half of your question:
The is
operator checks if the memory locations of the two operands are the same, despite whether they are to be considered identical. The best analogy I can think of for this right now, is identical twins. Consider that you have two friends, who are identical twins. While it may be easy to confuse one for the other, while looking at them individually, if you track their GPS coordinates, you'll likely to never make that mistake.
Along those lines, the is
operator checks for the specific location in memory (RAM) where the operands are held and returns True
only if both operands point to the same memory location (in much the same way as you'd confuse the two twins only if they were standing on the exact same coordinates).
Now, in many cases, if a is b
and if a==b
work the same. This happens with immutable types like int
s and str
s (this isn't entirely true depending on how you build your str
s; for example, 'abc'=='ab'+'c'
is True, but 'abc' is 'ab'+'c'
is not) and -- drumroll please -- NoneType
s.