8

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)
2

1 Answer 1

12

& 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

Sign up to request clarification or add additional context in comments.

2 Comments

In python, you can also customize the operator for a class. For example, adding def __and__(...) to Foo class, you can use Foo() & something
there is no type casting...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.