[Tutor] “has a value of True” versus “evaluates true”

Alan Gauld alan.gauld at btinternet.com
Tue Nov 11 23:29:59 CET 2014


On 11/11/14 20:04, Clayton Kirkwood wrote:
> So, there is a difference between None and False, is that the issue?

Yes. True and False are the only literal boolean values.
Everything else is boolean-like. That is, they can be used
in a boolean context and Python will treat them as if
they were either True or False, but they are not identical
to the literal values True and False.

So if you use None as a boolean expression in an if test it will be 
treated like it was False. But if you compare it to literal False
using '==' or 'is' it will not be the same.

You can see that below:

 >>> if not None: print('Its true')
...
Its true
 >>> if not False: print('Its true')
...
Its true

So those two worked identically

 >>> if None == False: print('Its not true')
...
 >>> if None is False: print('Its not true')
...

But None is not the same as False since neither print() was called.

 >>> if bool(None) == False: print('Its true this time')
...
Its true this time
 >>>

But if we explicitly convert None to a boolean value it is False.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list