在&python中&和<和>等价吗?

Ale*_*lex 2 python operators bitwise-operators boolean-operations

在Python 中使用单词and&符号的逻辑或性能有什么不同吗?

Nay*_*uki 7

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返回a.
  • 否则TypeError引发a(例如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'