A = 314
if A == A == A:
print('True #1')
if A == A == 271:
print('True #2')
lie = 0
if lie is lie is lie:
print('no matter how white, how small,')
print('how incorporating of a smidgeon')
print('of truth there be in it.')
结果:
True #1
no matter how white, how small,
how incorporating of a smidgeon
of truth there be in it.
我知道在 if 语句中使用两个“=”和“is”是不正常的。但我想知道Python解释器如何解释if
声明。
表达式是 lie is lie is lie
同时解释,还是短路方式?
您遇到的情况称为“运算符链”。
来自 Comparisons 的文档:
Comparisons can be chained arbitrarily, e.g., x < y <= z
is equivalent to x < y and y <= z
, except that y
is evaluated only once (but in both cases z
is not evaluated at all when x < y
is found to be false).
强调我的。
所以,这意味着 lie is lie is lie
被解释为(lie is lie) and (lie is lie)
,仅此而已。
更一般地说,a op b op c op d ...
评估结果与 a op b and b op c and c op d ...
相同等等。根据python的grammar rules解析表达式。特别是;
comparison ::= or_expr ( comp_operator or_expr )*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
我是一名优秀的程序员,十分优秀!