【问题标题】:python outputs None twicepython输出None两次
【发布时间】:2015-10-01 16:34:14
【问题描述】:

我在 Python 2.7.10 中运行了以下代码:

count = 1
for i in (False, None):
    print count
    count += 1
    if i is None:
        print i
    if not i:
        print i

输出是

1
False
2
None
None

如果我运行代码:

count = 1
for i in (False, None):
    print count
    count += 1
    if i is None:
        print i

输出是:

1
2
None

为什么在第一种情况下 None 打印两次。

【问题讨论】:

  • if not ii 为无时执行。
  • None 为假。因此,if not i 将在 iNone 时为真。
  • 应得的负刻度

标签: python python-2.7


【解决方案1】:

你错过了什么; 两者 if 条件为真:

>>> i = None
>>> i is None
True
>>> not i
True

Noneconsidered false in a boolean contextnot false 为 true;引用文档:

可以测试任何对象的真值,用于ifwhile 条件或作为以下布尔运算的操作数。以下值被认为是错误的:

  • None

[....]

所有其他值都被认为是真——所以许多类型的对象总是真。

if i is None:if not i: 都通过了,您将打印两次 i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多