惯用的Python-检查零 [英] Idiomatic Python - checking for zero

查看:66
本文介绍了惯用的Python-检查零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中检查零值的惯用方式是什么?

What is the idiomatic way for checking a value for zero in Python?

if n == 0:

if not n:

我认为第一个是更明确的精神,但另一方面,类似于第二个示例,将检查空序列或None.

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 n == 0 .您的第二个表达式不检查零,而是检查任何值为false的值.

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.

我认为答案就在于您的要求;您是否真的想检查零,还是要处理n可能是非数字类型的很多情况?

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?

本着准确回答所提问题的精神,我认为 n == 0 是可行的方法.

In the spirit of answering exactly the question asked, I think n == 0 is the way to go.

这是 not n 路线的问题所在:

>>> def isZero(n):
...    return not n;
... 
>>> 
>>> isZero([])
True
>>> isZero(False)
True
>>> isZero("")
True
>>> 

大多数人会说此"isZero"功能不正确.

Most people would say that this "isZero" function isn't correct.

这篇关于惯用的Python-检查零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆