Why do integers compare equal to booleans?
Santiago Basulto
santiago at rmotr.com
Fri Nov 16 10:33:14 EST 2018
> Because Python used not to have a boolean type and used the integers 0
and 1 instead
Exactly as Jon says. I wrote a post some time ago with more info about it:
https://blog.rmotr.com/those-tricky-python-booleans-2100d5df92c
On Fri, Nov 16, 2018 at 12:23 PM duncan smith <duncan at invalid.invalid>
wrote:
> 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
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
Santiago Basulto.-
Co-founder @ rmotr.com
More information about the Python-list
mailing list