Ikbear
Ikbear

Reputation: 1307

Unbelievable python boolean feature

>>> a = False
>>> b = False
>>> a | b
True
>>> a
True
>>> b
True

I get this in a python interpreter.

I just don't think so. Is there any detailed material about python boolean type?

I use Python 2.6.6, thanks!

Upvotes: 1

Views: 864

Answers (3)

Daniel G
Daniel G

Reputation: 69792

I can see only one context in which your problem makes sense:

>>> False = True
>>> a = False
>>> b = False
>>> a | b
True
>>> a
True
>>> b
True
>>> 

To start debugging - what's the result of print int(False)? If the above happened, you should get 1. Try:

>>> False = bool(0)
>>> a = False
>>> b = False
>>> a | b
False

As far as why this happened - maybe someone played a prank on you and changed the value of False (see this answer)? I really can't think of anything else that would cause this. You could always set False to bool(0) in modules where you need it, to guard against this.

Or switch to Python 3, which makes True and False reserved words which can't be changed.

Upvotes: 7

Jochen Ritzel
Jochen Ritzel

Reputation: 107786

Something is wrong with your interpreter:

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> False | False
False
>>> a = False
>>> b = False
>>> a | b
False

Upvotes: 4

sahhhm
sahhhm

Reputation: 5365

| is the bitwise-or operator in python.

If you're doing a conditional check you should use the or operator:

>>> a = False
>>> b = False
>>> a or b
False
>>> a
False
>>> b
False

You can read more about bitwise operators here.

Edit/Side Note: After running the code you posted in your question, I am not getting the same results... there may be something wrong with your installation...

Upvotes: 2

Related Questions