如标题所言:
- and(or):boolean operator
- &(|):bitwise operator
二者的主要区别在于:
- boolean 算子(and/or)主要用于布尔值(
True
/False
),而位操作子(bitwise operator,&
/|
)通常用于整型之间
>>> b1 = [True, True, True, False, True]
>>> b2 = [False, True, False, True, False]
>>> b1 and b2
[False, True, False, True, False]
>>> b1 & b2
TypeError: unsupported operand type(s) for &: 'list' and 'list'
- 布尔算子支持骤死式(侯捷译,short-circuiting behavior)的评估方式,位操作符不支持:
所谓骤死式
的评估方式,即为一旦该表达式的真假值确定,即使表达式中还有部分尚未检验,整个评估工作仍告结束。
骤死式
的表达方式常用语如下的语句:
if x is not None and x.foo == 42:
# ...
如果将这里的 and
换成 &
,将会导致不必要的异常(AttributeError: 'NoneType' object has no attribute 'foo'
,如果 x is not None
不成立),因为对 &
而言,&
两边都要被评估。
When you use the boolean
and
operator the second expression is not evaluated when the first is False. (当使用and
算子时,如果左侧判断为假,将不会判断右侧的语句的真假,因为是徒劳的,无论第二条语句为真还是为假,结果总是为假)Similarly
or
does not evaluate the second argument if the first is True.(当使用or
算子时,如果左侧判断为真,将不会判断右侧语句的真假,因为也是徒劳的,即无论第二条语句为真还是为假,结果总为真)
>>> 5 and 6
6
# 左侧为真,
# 接着判断右侧
>>> 0 and 6
0
# 左侧为假,骤死式,
# 不再判断右侧
>>> 5 or 6
5
# 左侧为真,骤死式
# 不在判断右侧
>>> 0 or 6
6
# 左侧为假,
# 接着判断右侧