6

The first code gives True but the second gives an error saying

TypeError: unsupported operand type(s) for &: 'str' and 'int'

What is the difference between & and and operator in Python? Isn't it the same?

student = "Justin"

first code

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

second code

print(student == "Justin" & 1 == 1)
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
Justin M
  • 177
  • 1
  • 3
  • 11

1 Answers1

9

& is the bit-AND operator.

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

while and is the boolean operator.

You can use & for boolean expression and get correct answer since True is equivalent to 1 and False is 0, 1 & 0 = 0. 0 is equivalent to False and Python did a type casting to Boolean. That's why you get boolean result when using & for booleans

Tuan Chau
  • 1,243
  • 1
  • 16
  • 30