[Tutor] use the data None

Corey Richardson corey at octayn.net
Mon Jun 4 00:08:12 CEST 2012


On Sun, 3 Jun 2012 23:43:30 +0200
Tehn Yit Chin <tehn.yit.chin at gmail.com> <tehn.yit.chin at gmail.com> wrote:

> Hi all,
> 
> 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"
> 

The proper idiom, for a variety of reasons, is:

if abc is not None:
	# do stuff

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

No. It will raise a NameError, which you would have to catch. To do
what you want, something along the lines of:

try:
	abc
	# it exists
except NameError:
	# it doesn't

However, this is pretty dirty. Why are you using variables that
potentially don't exist?

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

For a generic foo,

if foo not in abc:
	# it's not there, Jim

Does this answer your questions?

(I've been away from Python for a bit, one of the other tutors might
correct me with better practice things, I'm rusty!)

-- 
Corey Richardson


More information about the Tutor mailing list