python中的“如果不是”条件语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34376441/
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
"If not" condition statement in python
提问by kaka
if not start:
new.next = None
return new
what does "if not" mean? when will this code execute?
“如果不是”是什么意思?这段代码什么时候执行?
is it the same thing as saying if start == None: then do something?
这与说 if start == None: then do something 一样吗?
采纳答案by Martijn Pieters
ifis the statement. not startis the expression, with notbeing a boolean operator.
if是声明。not start是表达式,not是一个布尔运算符。
notreturns Trueif the operand (starthere) is considered false. Python considers all objects to be true, unless they are numeric zero, or an empty container, or the Noneobject or the boolean Falsevalue. notreturns Falseif startis a true value. See the Truth Value Testingsectionin the documentation.
not返回True如果操作数(start在这里)被认为是假的。Python 认为所有对象都为真,除非它们是数字零、空容器、None对象或布尔False值。如果是真值则not返回。请参阅文档中的真值测试部分。Falsestart
So if startis None, then indeed not startwill be true. startcan also be 0, or an empty list, string, tuple dictionary, or set. Many custom types can also specify they are equal to numeric 0 or should be considered empty:
所以如果start是None,那么确实not start会是真的。start也可以是0,或空列表、字符串、元组字典或集合。许多自定义类型还可以指定它们等于数字 0 或应视为空:
>>> not None
True
>>> not ''
True
>>> not {}
True
>>> not []
True
>>> not 0
True
Note: because Noneis a singleton (there is only ever one copy of that object in a Python process), you should always test for it using isor is not. If you strictlywant to test tat startis None, then use:
注意:因为None是单例(在 Python 进程中只有该对象的一个副本),所以您应该始终使用is或对其进行测试is not。如果您严格想要测试 tat startis None,请使用:
if start is None:
回答by Pynchia
It executes when startis False, 0, None, an empty list [], an empty dictionary {}, an empty set...
它在startis False、0、None、空列表[]、空字典{}、空集时执行...

