Idiomatic Python - checking for zero

断了今生、忘了曾经 提交于 2019-12-11 06:16:54

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23610416/idiomatic-python-checking-for-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!