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:10: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"
The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False . Understanding how Python Boolean values behave is important to programming well in Python.
Numbers. In Python, the integer 0 is always False , while every other number, including negative numbers, are True .
In programming languages value of True is considered as 1. whereas false is zero. therefore In Boolean algebra True + False=1+0=1.
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 >>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With