[Tutor] Question about the use of None

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Jun 11 17:07:46 EDT 2004

> Hi,I came across this keyword None. The document I read says
> "None is python's way of representing nothing.

That is to say nothingat all, not even an empty string or zero.

> It evaluates to False when treated as a condition

So its boolean value is False, just as "" is False and 0 is false.
BUt None is not the same as "" any more than 0 is the same as "",
they are three things that evaluate to False in boolean terms.

> "So I assume, if I do start=None, then it's as good as saying
> start="" or start=0

Thats right because they all evaluate to False.

> Now, the code to represent it's use is pretty confusing.

No, its totally consistent! ;-)

> It goes like this:
while start != "":
     start=raw_input("Press enter to exit, or key in a string: ")

The confusing part is here, since start = "",

No start is None wjich is NOT the same thing as "".
If the test was

while not start:

Then you would be right, because both None and "" would cause the
loop test to fail. But while start != "" will be true for anything
except an empty string which will only occur when the user hits
return with no content.

> at least that's if None is really == ""

But None is not the same as "" any more than 0 is the same as "".
They just evaluate as Booleans to False. (As does an empty list BTW)

> So to check, I tried this in the interactive window:
>>> start=None
>>> print start

Will print the string representation of None which is, not
surprisingly 'None'. Remember that the prompt uses the result
of the __repr__() function and print uses the result of the
__str__() function.

> and presto !! It prinst the string None, even though i haven't
> placed it in double quotes.

If you had placed it in double quootes ythey would not ave appeared:

>>> print "None"
>>> print None

> So it seems None does have a value,

No it has a string representation, just like almost every other Python
object. (Even though None is actually a non-object!!)

> which explains why it managed to enter the while loop. Is this

No, it entered the loop because None is something different from ""

>>> print None == ""
>>> print None
>>> print 0 == ""
>>> if not 0: print '0 is false'
0 is false
>>> if not "": print "'' is false"
'' is false
>>> if not None: print "None is false"
None is false
>>> if not None and not "": print 'None and "" are both false'
None and "" are both false

> Hope someone can help with an explanation.

Well, I've tried! :-)

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list