和python中的操作

以下是产生令人困惑的结果的代码。

a = None
b = 1
print a and b
if a and b is None:
    print "True"
else:
    print "False"

这里 bool(a) 是假的,因为它没有。所以通过短路,表达式应该返回 None。这实际上正在发生。但是,在 if 条件期间,条件失败。尽管 a 和 b 产生 None,但条件失败并在输出中显示 false。有人可以解释为什么会这样吗?

回答

a and b is None计算结果与 相同a and (b is None),因此表达式计算结果为 None,并且执行跳转到 else 子句。

如果您添加括号(a and b) is None,那么您的代码将按您的预期打印“True”。

这是因为isandPython具有更高的优先级。有关更多详细信息,请查看运算符优先级文档。

  • The term for this is operator precedence: `is` has the same precedence as `==` and the other comparators, which makes intuitive sense.

以上是和python中的操作的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>