Python中"&"和"and"的区别是什么?

6
第一段代码返回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)

2
and 是一个布尔运算符,& 是一个按位与运算符,并且它具有更高的优先级。 - juanpa.arrivillaga
1
一个好的解释 https://www.geeksforgeeks.org/difference-between-and-and-in-python/ - sagar1025
1个回答

10

& 是位与运算符。

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

在 Python 中,and 是一个布尔运算符。

当你使用 & 进行布尔表达式时,由于 True 等同于 1,False 等同于 0,因此你可以得到正确的结果。例如,1 & 0 = 0。0 等同于 False,Python 进行了一个类型转换来生成布尔值结果。这就是为什么使用 & 进行布尔运算会返回布尔结果的原因。


1
在Python中,您还可以为类自定义运算符。例如,向Foo类添加def __and__(...),您就可以使用Foo() & something - Tuan Chau
1
没有类型转换... - juanpa.arrivillaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接