1

以下代码:

a,b=1,2
print((x:=a)<2<(z:=b) or z>1>x)
print((x:=a)<1<(y:=b) or y>1>x)

给出以下输出:

False
Traceback (most recent call last):
  File "C:/Users/phili/PycharmProjects/ML 1/CodingBat exercises.py", line 56, in <module>
    print((x:=a)<1<(y:=b) or y>1>x)
NameError: name 'y' is not defined

这似乎完全不一致。一些变化,比如 (x:=1)>=2>(y:=9) or y>=2>x 也给出

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

有谁知道发生了什么?

4

1 回答 1

1

显然链式运算符短路。您可以在此示例代码中看到这一点:

>>> 1 < 1 < print("Nope")
False  # Nothing else is printed

这很可能是因为

a < b < c

本质上是简写

a < b and b < c

and短路:

>>> False and print("Nope")
False

这意味着由于左侧检查为 False,因此永远不会评估右侧,因此y永远不会设置。

于 2020-09-10T19:54:22.183 回答