variable question

norseman norseman at hughes.net
Thu Jul 10 13:03:01 EDT 2008


Support Desk wrote:
> I am trying to assign a variable using an if / else statement like so:
> 
>  
> 
> If condition1:
> 
>             Variable = something
> 
> If condition2:
> 
>             Variable = something else
> 
> Do stuff with variable.
> 
>  
> 
> But the variable assignment doesn't survive outside the if statement. Is
> there any better way to assign variables using an if statement or exception
> so I don't have to write two almost identical if statements. This is
> probably a dumb question.
> 
> 
> 
> 
> ------------------------------------------------------------------------
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
===================================

Is this test in a def?  If in-line there should be no problem if Var is 
done as this:

var= ' '
test= '2'
if test == '1':
   var= 'choice 1'
elif test == '2':
   var= 'choice 2'
elif test == '3':
   var= 'default'
#endif
#do something with var

print var
         -----------------

if inside a def:

var= 0
def xxx():
   global var
   var += 1     # whatever, if var was set to text, do text things
   #possible other commands
#enddef
# somewhere below in 'main' (runtime portion of code)

xxx()
print var  #use var, etc. etc.

         -----------------

It is ALWAYS good form to prime a var before using.



Steve
norseman at hughes.net



More information about the Python-list mailing list