osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why do integers compare equal to booleans?


On 16/11/18 14:51, Steve Keller wrote:
> Why do the integers 0 and 1 compare equal to the boolean values False
> and True and all other integers to neither of them?
> 
>     $ python3
>     Python 3.5.2 (default, Nov 12 2018, 13:43:14)
>     [GCC 5.4.0 20160609] on linux
>     Type "help", "copyright", "credits" or "license" for more information.
>     >>> 0 == False
>     True
>     >>> 1 == True
>     True
>     >>> 2 == False
>     False
>     >>> 2 == True
>     False
>     >>> -1 == False
>     False
>     >>> -1 == True
>     False
>     >>>
> 
> Since these are objects of different types I would expect they cannot
> be equal.  I know that 0 means false and != 0 means true in C, C++,
> etc. but in Python that surprises me.
> 
> Steve
> 

>>> isinstance(False, int)
True
>>> isinstance(True, int)
True
>>> False.real
0
>>> True.real
1
>>>

At least in recent Pythons.

Duncan