【问题标题】:what is the difference between "&" and "and" in Python? [duplicate]Python中的“&”和“and”有什么区别? [复制]
【发布时间】:2021-08-11 04:10:55
【问题描述】:

第一个代码给出 True,但第二个代码给出一个错误“TypeError: unsupported operand type(s) for &: 'str' and 'int'”。

Python中的“&”和“and”运算符有什么区别?不一样吗?

student = "Justin"

第一个代码

print(student == "Justin" and 1 == 1)

第二个代码

print(student == "Justin" & 1 == 1)

【问题讨论】:

标签: python operator-keyword


【解决方案1】:

& 是位与运算符。

1 & 1 = 1
3 & 2 = 2
2 & 1 = 0

而and 是布尔运算符。

您可以使用& 进行布尔表达式并得到正确答案,因为True 等于1,False 等于0,1 & 0 = 0。 0 相当于 False 并且 Python 对布尔值进行了类型转换。这就是为什么在使用 & 作为布尔值时会得到布尔结果

【讨论】:

  • 在python中,你也可以自定义一个类的操作符。例如,将def __and__(...)添加到Foo类中,可以使用Foo() & something
  • 没有类型转换...
猜你喜欢
  • 2011-07-29
  • 1970-01-01
  • 2011-06-12
  • 2015-05-18
  • 2010-12-10
  • 2016-08-24
  • 2016-02-16
  • 1970-01-01
  • 2014-02-24
相关资源
最近更新 更多