Are & and <and> equivalent in python? [duplicate]

假如想象 提交于 2021-02-19 05:42:08

问题


Is there any difference in the logic or performance of using the word and vs. the & symbol in Python?


回答1:


and is a Boolean operator. It treats both arguments as Boolean values, returning the first if it's falsy, otherwise the second. Note that if the first is falsy, then the second argument isn't even computed at all, which is important for avoiding side effects.

Examples:

  • False and True --> False
  • True and True --> True
  • 1 and 2 --> 2
  • False and None.explode() --> False (no exception)

& has two behaviors.

  • If both are int, then it computes the bitwise AND of both numbers, returning an int. If one is int and one is bool, then the bool value is coerced to int (as 0 or 1) and the same logic applies.
  • Else if both are bool, then both arguments are evaluated and a bool is returned.
  • Otherwise a TypeError is raised (such as float & float, etc.).

Examples:

  • 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'


来源:https://stackoverflow.com/questions/32941097/are-and-and-equivalent-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!