英文:
Python: real order of execution for equalities/inequalities in expressions?
问题
请看下面这段“狡猾”的Python代码:
>>> 1 == 2 < 3
False
根据Python文档,所有运算符in, not in, is, is not, <, <=, >, >=, !=, ==
的优先级相同,但这里发生的情况似乎矛盾。
在实验后,我得到了更奇怪的结果:
>>> (1 == 2) < 3
True
>>> 1 == (2 < 3)
True
发生了什么?
(注意)
>>> True == 1
True
>>> True == 2
False
>>> False == 0
True
>>> False == -1
False
布尔类型是int
的子类,True代表1,False代表0。
这可能是一个实现细节,不同版本可能会有所不同,所以我主要关心的是Python 3.10版本。
英文:
Imagine this "sneaky" python code:
>>> 1 == 2 < 3
False
According to Python documentation all of the operators in, not in, is, is not, <, <=, >, >=, !=, ==
have the same priority, but what happens here seems contradictory.
I get even weirder results after experimenting:
>>> (1 == 2) < 3
True
>>> 1 == (2 < 3)
True
What is going on?
(Note)
>>> True == 1
True
>>> True == 2
False
>>> False == 0
True
>>> False == -1
False
Boolean type is a subclass of int
and True represents 1
and False represents 0
.
This is likely an implementation detail and may differ from version to version, so I'm mostly interested in python 3.10.
答案1
得分: 1
Python允许您链接条件,它使用and
来组合它们。所以
1 == 2 and 2 < 3
等同于
1 == 2 and 2 < 3
这在不等式链中非常有用,例如 1 < x < 10
将在 x
在 1
和 10
之间时为真。
当您添加括号时,它不再是一个链。所以
(1 == 2) < 3
等同于
False < 3
True
和 False
等同于 0
和 1
,因此 False < 3
与 0 < 3
是相同的,也就是 True
。
类似地,
1 == (2 < 3)
等同于
1 == True
这等同于
1 == 1
显然是 True
。
英文:
Python allows you to chain conditions, it combines them with and
. So
1 == 2 < 3
is equivalent to
1 == 2 and 2 < 3
This is most useful for chains of inequalities, e.g. 1 < x < 10
will be true if x
is between 1
and 10
.
WHen you add parentheses, it's not a chain any more. So
(1 == 2) < 3
is equivalent to
False < 3
True
and False
are equivalent to 0
and 1
, so False < 3
is the same as 0 < 3
, which is True
.
Similarly,
1 == (2 < 3)
is equivalent to
1 == True
which is equivalent to
1 == 1
which is obviously True
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论