【问题标题】:"If not" condition statement in python [duplicate]python中的“如果不是”条件语句[重复]
【发布时间】:2016-03-26 09:24:17
【问题描述】:
if not start: 
   new.next = None 
   return new

“如果不是”是什么意思? 这段代码什么时候执行?

和说的一样吗 如果 start == None:那么做点什么?

【问题讨论】:

  • if 是声明。 not start 是表达式,not 是运算符。
  • @rnrneverdies 虽然这是一个很好的问题,但我认为这并不能说明 OP 的困惑(例如,if not 做了什么?)。相反,它讨论了if <expr>if <expr>==<value>if <expr> is <value> 之间的区别

标签: python if-statement conditional


【解决方案1】:

if 是声明。 not start 是表达式,notboolean operator

not 如果操作数(此处为start)被认为是false,则返回True。 Python 认为所有对象都为真,除非它们是数字零、空容器、None 对象或布尔值False。如果start 为真值,not 返回False。请参阅文档中的Truth Value Testing section

所以如果startNone,那么not start 确实是真的。 start 也可以是0,也可以是空列表、字符串、元组字典或集合。许多自定义类型还可以指定它们等于数字 0 或应视为空:

>>> not None
True
>>> not ''
True
>>> not {}
True
>>> not []
True
>>> not 0
True

注意:因为None 是一个单例(在 Python 进程中该对象只有一个副本),所以您应该始终使用isis not 对其进行测试。如果您严格想要测试startNone,那么使用:

if start is None:

【讨论】:

    【解决方案2】:

    startFalse0None、一个空列表[]、一个空字典{}、一个空集时执行...

    【讨论】:

      猜你喜欢
      • 2015-02-12
      • 2020-09-23
      • 2016-12-17
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 2015-08-20
      • 1970-01-01
      相关资源
      最近更新 更多