The Python Oracle

Why does 1 == True but 2 != True in Python?

This video explains
Why does 1 == True but 2 != True in Python?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
01:17 Accepted answer (Score 36)
02:04 Answer 2 (Score 28)
02:29 Answer 3 (Score 13)
03:03 Answer 4 (Score 12)
03:34 Thank you

--

Full question
https://stackoverflow.com/questions/7134...

Question links:
[Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?]: https://stackoverflow.com/questions/2764...

Accepted answer links:
[http://docs.python.org/library/stdtypes....]: http://docs.python.org/library/stdtypes....

Answer 4 links:
[PEP 285]: http://www.python.org/dev/peps/pep-0285/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 37


Because Boolean in Python is a subtype of integers. From the documentation:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

http://docs.python.org/library/stdtypes.html#boolean-values




ANSWER 2

Score 28


Because instances of bool are also instances of int in python. True happens to be equals to integer 1.

Take a look at this example:

[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(True, int)
True
>>> int(True)
1
>>> 



ANSWER 3

Score 13


It's standard binary conventions: 1 is true, 0 is false.

It's like 1 means "on" in machine language, and 0 means "off".

Because of this the bool type is just a subtype of int in Python, with 1 == True and 0 == False.

However any non-zero numeric value will be evaluated as True in a conditional statement:

>>> if 2: print "ok"
ok
>>> 2 == True
False



ANSWER 4

Score 5


Equality testing is different than boolean testing:

>>> bool(1)
True
>>> bool(2)
True
>>> bool(-1)
True
>>> bool(0)
False