Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

I'm a big proponent of say what you mean. Your two statements mean different things. The first means:

if n equals 0

whereas the second means:

if the truth value of n is False

While they have the same effect in practice for integers, the actual meaning should dictate which you use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top