What is the idiomatic way for checking a value for zero in Python?
if n == 0:
or
if not n:
I would think that the first one is more in the spirit of being explicit but on the other hand, empty sequences or None is checked similar to the second example.
If you want to check for zero, you should use if n == 0
. Your second expression doesn't check for zero, it checks for any value that evaluates as false.
I think the answer lies in your requirements; do you really want to check for zero, or do you want to handle a lot of situations where n might be a non-numeric type?
In the spirit of answering exactly the question asked, I think n == 0
is the way to go.
Here's what's wrong with doing it the not n
route:
>>> def isZero(n):
... return not n;
...
>>>
>>> isZero([])
True
>>> isZero(False)
True
>>> isZero("")
True
>>>
Most people would say that this "isZero" function isn't correct.