Implicit conversion to boolean in if and while statements

John Nagle nagle at animats.com
Tue Jul 17 09:26:50 CEST 2012


On 7/15/2012 1:34 AM, Andrew Berg wrote:
> This has probably been discussed before, but why is there an implicit
> conversion to a boolean in if and while statements?
>
> if not None:
> 	print('hi')
> prints 'hi' since bool(None) is False.
>
> If this was discussed in a PEP, I would like a link to it. There are so
> many PEPs, and I wouldn't know which ones to look through.
>
> Converting 0 and 1 to False and True seems reasonable, but I don't see
> the point in converting other arbitrary values.

    Because Boolean types were an afterthought in Python.  See PEP 285.
If a language starts out with a Boolean type, it tends towards
Pascal/Ada/Java semantics in this area.  If a language backs
into needing a Boolean type, as Python and C did, it tends to have
the somewhat weird semantics of a language which can't quite decide 
what's a Boolean.  C and C++ have the same problem, for exactly the
same reason - boolean types were an afterthought there, too.

					John Nagle



More information about the Python-list mailing list