Python 布尔操作(and/or,Boolean operator)与位操作(&/|,Bitwise operator)

来源:互联网 发布:网络推广属于哪个部门 编辑:程序博客网 时间:2024/05/17 09:34

如标题所言:

  • 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 & b2TypeError: 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 66                    # 左侧为真,                    # 接着判断右侧        >>> 0 and 60                    # 左侧为假,骤死式,                    # 不再判断右侧>>> 5 or 65                    # 左侧为真,骤死式                    # 不在判断右侧>>> 0 or 66                    # 左侧为假,                    # 接着判断右侧

References

[1] Python: Boolean operators vs Bitwise operators

0 0