是&amp;和<和>等效的python?

时间:2015-10-05 04:04:12

标签: python operators bitwise-operators boolean-operations

在Python中使用单词and&符号的逻辑或性能是否存在差异?

1 个答案:

答案 0 :(得分:6)

and是一个布尔运算符。它将两个参数视为布尔值,如果它是假的则返回第一个,否则返回第二个。注意,如果第一个是假的,那么第二个参数甚至根本不算计算,这对避免副作用很重要。

示例:

  • False and True --> False
  • True and True --> True
  • 1 and 2 --> 2
  • False and None.explode() --> False(也不例外)

&有两种行为。

  • 如果两者都是int,则它计算两个数字的按位AND,返回int。如果一个是int且一个是bool,则bool值被强制转换为int(为0或1)并且适用相同的逻辑。
  • 否则如果两者都是bool,则会评估两个参数并返回bool
  • 否则会引发TypeError(例如float & float等)。

示例:

  • 1 & 2 --> 0
  • 1 & True --> 1 & 1 --> 1
  • True & 2 --> 1 & 2 --> 0
  • True & True --> True
  • False & None.explode() --> AttributeError: 'NoneType' object has no attribute 'explode'