Python“如果不是”语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16739555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 'If not' syntax
提问by Edgar Aroutiounian
I'm a bit confused about how/why so many python developers use if notin their conditional statements.
我对这么多 python 开发人员如何/为什么if not在他们的条件语句中使用感到有些困惑。
for example, lets say we had a function,
例如,假设我们有一个函数,
def foo(bar = None):
if not bar:
bar = 2
But why go about this way? I mean, wouldn't doing if bar != Noneor if bar is not Nonebe more explicit? What does if nottry to say?
但是为什么要走这条路呢?我的意思是,不会做if bar != None或者if bar is not None更明确吗?什么是if not尝试说?
采纳答案by Edgar Aroutiounian
Yes, if bar is not Noneis 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 baris any kind of zero or empty container, or False.
Many people do use not barwhere they really domean bar is not None.
是的,if bar is not None更明确,因此更好,假设它确实是您想要的。情况并非总是如此,存在细微差别:if not bar:如果bar是任何类型的零或空容器,或False. 许多人确实not bar在他们真正的意思的地方使用bar is not None。

