为什么不与QUOT;和"和"或QUOT;在Python运营商? [英] Why aren't "and" and "or" operators in Python?
问题描述
我不知道这一点,但显然和
和或
关键字不是运营商。它们不会出现在Python运营商的列表。只是出于好奇心十足,这是为什么?如果他们不是运营商,究竟是什么人?
I wasn't aware of this, but apparently the and
and or
keywords aren't operators. They don't appear in the list of python operators. Just out of sheer curiosity, why is this? And if they aren't operators, what exactly are they?
推荐答案
由于他们控制流结构。具体做法是:
Because they're control flow constructs. Specifically:
- 如果左边的参数
和
的值为False,正确的说法没有得到所有评估 - 如果左边的参数
或
评估为真,正确的说法没有得到所有评估
- if the left argument to
and
evaluates to False, the right argument doesn't get evaluated at all - if the left argument to
or
evaluates to True, the right argument doesn't get evaluated at all
因此,它不是简单的是保留字的问题。他们不表现得像运营商,因为运营商始终评估所有他们的论据。
Thus, it is not simply a matter of being reserved words. They don't behave like operators, since operators always evaluate all of their arguments.
您可以按位二进制运算对比这其中,顾名思义,的是的运营商:
You can contrast this with bitwise binary operators which, as the name implies, are operators:
>>> 1 | (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 1 or (1/0)
1
正如你所见,按位或( |
)的计算结果都它的参数。在或
关键词,然而,这不是在所有的时候左边的参数值为True评估其右边的参数;这就是为什么没有 ZeroDivisionError
引发的第二个语句。
As you see, the bitwise OR (|
) evaluates both its arguments. The or
keyword, however, doesn't evaluate its right argument at all when the left argument evaluates to True; that's why no ZeroDivisionError
is raised in the second statement.
这篇关于为什么不与QUOT;和&QUOT;和&QUOT;或QUOT;在Python运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!