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
if
is the statement. not start
is the expression, with not
being a boolean operator.
if
是声明。not start
是表达式,not
是一个布尔运算符。
not
returns True
if the operand (start
here) is considered false. Python considers all objects to be true, unless they are numeric zero, or an empty container, or the None
object or the boolean False
value. not
returns False
if start
is a true value. See the Truth Value Testingsectionin the documentation.
not
返回True
如果操作数(start
在这里)被认为是假的。Python 认为所有对象都为真,除非它们是数字零、空容器、None
对象或布尔False
值。如果是真值则not
返回。请参阅文档中的真值测试部分。False
start
So if start
is None
, then indeed not start
will be true. start
can 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 None
is a singleton (there is only ever one copy of that object in a Python process), you should always test for it using is
or is not
. If you strictlywant to test tat start
is None
, then use:
注意:因为None
是单例(在 Python 进程中只有该对象的一个副本),所以您应该始终使用is
或对其进行测试is not
。如果您严格想要测试 tat start
is None
,请使用:
if start is None:
回答by Pynchia
It executes when start
is False
, 0
, None
, an empty list []
, an empty dictionary {}
, an empty set...
它在start
is False
、0
、None
、空列表[]
、空字典{}
、空集时执行...