Python“如果不是"语法 [英] Python 'If not' syntax
问题描述
我对如此多的 Python 开发人员如何/为什么在他们的条件语句中使用 if not
感到有些困惑.
I'm a bit confused about how/why so many python developers use if not
in their conditional statements.
例如,假设我们有一个函数,
for example, lets say we had a function,
def foo(bar = None):
if not bar:
bar = 2
但是为什么要这样呢?我的意思是,if bar != None
或 if bar is not None
会不会更明确?if not
想说什么?
But why go about this way? I mean, wouldn't doing if bar != None
or if bar is not None
be more explicit? What does if not
try to say?
推荐答案
是的,if bar is not None
更明确,因此更好,假设它确实是您想要的.情况并非总是如此,存在细微差别:if not bar:
将在 bar
是任何类型的零或空容器或 False
时执行>.许多人确实使用 not bar
,而他们确实使用意味着 bar is not None
.
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
这篇关于Python“如果不是"语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!