Why does 1 == True but 2 != True in Python? [duplicate]
Possible Duplicate:
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
A brief transcript from my interactive console:
Python 2.7.2 (default, Jun 29 2011, 11:1开发者_如何学编程0:00)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True
True
>>> 0 == True
False
>>> 1 == True
True
>>> 2 == True
False
Why on earth is this the case?
Edit: For the sake of contrast, consider the is
operator.
>>> 0 is False
False
>>> 1 is True
False
>>> 0 is 0
True
>>> True is True
True
That makes a lot of sense because though 1
and True
both mean the same thing as the condition of an if
statement, they really aren't the same thing.
Edit again: More fun consequences of 1 == True
:
>>> d = {}
>>> d[True] = "hello"
>>> d[1]
"hello"
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
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
>>>
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
Once upon a time (in Python < 2.3), there was no boolean type, no False
or True
, only 0
and 1
. Then PEP 285 came along and thus they were added to the language. They were defined so that True == 1
and False == 0
, probably for reasons of backwards compatibility.
Equality testing is different than boolean testing:
>>> bool(1)
True
>>> bool(2)
True
>>> bool(-1)
True
>>> bool(0)
False
It's a boolean thing. 1 == true, 0 == false.
because in binary 1 is true and 0 is false. it also happens in PHP.
I'm not sure about other languages, but I think it's going to be the same.
It's binary. 0 is always False and 1 is always True. In python though any non-zero value, including negative values are always True.
>>> if -1:
... print 'a'
...
a
>>> if 2:
... print 'a'
...
a
>>> if 0:
... print 'a'
...
>>>
精彩评论