[Tutor] does a variable exist?

Daniel Coughlin kauphlyn@speakeasy.org
Tue, 5 Mar 2002 11:01:10 -0800 (PST)


Hi Henry,

One way to test whether or not your variable is set is with a try / except 
block.

for example

>>> try:
...	if a == 1:
...		print "a is 1"
...	else: print "a is not 1"
... except NameError, n:
...	print "a is not initialized"
a is not initialized

NameError is the exception that is raised when a local or global name is not 
found. n will be the be the actual exception. something like "a is not defined".
  

Hope this helps!


On Tue, 5 Mar 2002, Henry Porter wrote:

> I want to see if a variable exists in my program.  The variable is getting
> set within an 'if' statement, so sometimes it exists afterwards, but not
> always.  Is there a way to check for this besides just initializing it to
> something at the top of the program?
> 
> Thanks for any help,
> Henry
>