-1

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)
Justin M
  • 77
  • 1
  • 7

1 Answers1

1

& 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,045
  • 1
  • 14
  • 28