Steve Johnson
Steve Johnson

Reputation: 103

Strange behavior with & and | operators

Suppose type this into my python shell.

>>> print 0 != 1 and (1 == 1 or 2 == 2)
True

This returns the Boolean value True. Now let's suppose I change it up a little.

>>> print 0 != 1 & (1 == 1 | 2 == 2)
False

Now it returns False. Why?

Upvotes: 0

Views: 83

Answers (2)

Maroun
Maroun

Reputation: 95988

I think you're confusing & and &&. Note that in Python, && is the keyword and (As far as I know, && and || don't exist in Python).

| and & are binary AND and OR operators, which are really different from and and or.

Your second code is translated to:

0 != 1 & (1 == (1 | 2) == 2) # 1 | 2 is 3

      ↓↓

0 != 1 & (1 == 3 == 2)

      ↓↓

0 != 1 & int(False)

      ↓↓

0 != 1 & 0 # 1 & 0 is 0

Now, 0 != 0 is False.

Also please note the other answer about operator precedence.

Upvotes: 8

Kos
Kos

Reputation: 72279

https://docs.python.org/2/reference/expressions.html#operator-precedence

| and & have higher priority than != and ==.

Upvotes: 3

Related Questions