[Tutor] use the data None

Alan Gauld alan.gauld at btinternet.com
Mon Jun 4 02:39:10 CEST 2012

On 03/06/12 22:43, Tehn Yit Chin wrote:

> I am trying to understand when it is appropriate to use None as in the
> following example
> if abc != None:
>        print "abc is not None"

In general I only use that idf its a defaulted parameter to a function:

def foo(x=None):
    if x is None:
       do the default thing with x
       use the x that was passed in.

> 1) Can I use it to determine if the variable abc exists?

There are better ways of doing that, usually by detecting a NameErropr.

> 2) Can I use it to determine if the variable abc does not contain anything?

That's not the same as None

a = ''   # empty string
b = 0    # zero number
c = []   # empty list

usually you detect emptiness by a simply truth test:

for var in (a,b,c):
    if not var:
       print var.__name__, ' is empty or false'
       use the value

That's because, by convention, Python types assign falseness to be the 
same as emptiness, certainly for the built-in or standard types.

There are occasional uses for None but mostly it's there to make the 
language consistent! eg. a return type for functions that don't
explicitly return anything...

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list