Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between "&" and "and" in Python? [duplicate]

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)
like image 501
Justin M Avatar asked Jun 18 '26 12:06

Justin M


1 Answers

& 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

like image 75
Tuan Chau Avatar answered Jun 20 '26 01:06

Tuan Chau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!