[Tutor] Local/Global Variable

orbitz at ezabel.com orbitz at ezabel.com
Mon Jun 14 21:51:56 EDT 2004


The eror only shows itself when you do semthing like:

globalvar = 1

def foo():
  globalvar += 1

The interpreter see's yoau re assignign, and decides to think it's a local
variable.

The remedy is easy:
def foo():
  global globalvar
  globalvar += 1

You don't need to do it in every loop ro anything, since loops don't have thier
own scope  Anything you wish to do this with, you just can do it at the
beginning of your method, or before you use the variable atleast.

On Mon, 14 Jun 2004 21:08:54 EDT
Dragonfirebane at aol.com wrote:

> It is my understanding that if python does not find a variable locally, it is 
> coded to look for it globally. However, every time i attempt to run a certain 
> program, it comes up with an UnboundLocalError despite the fact that i 
> defined the variable outside of the loop in the outermost area of code. Short
> of inserting 'global variablename' in every loop, is there any way to remedy
> this? Relevant segment(s) of code:
> 
> def convertnum():
>     if whichconv in('1','Binary','binary','Bin','bin','B','b'): 
>         if int(original) <= 0:                                  
>             print "Please enter a positive number. "
>         try:
>             int(original)
>         except ValueError:
>             x = 0
>             for char in original:
>                 if char in punct:
>                     res += char
>                 x += 1
>         else:
>             asOctal = "%o" % int(original)
>             for char in asOctal:
>                 res += str(binary[char])    ##heres the problem . . .
> 
>     ...
> ...
> res = ''
> again = True
> while again:
>     ...
>     original = raw_input("Please enter numbers or text to be converted. ")
>     ...
>     str(original)
>     convertnum()
>     print res
> 
> 
> Error:
> 
> Traceback (most recent call last):
>   File "C:\Program Files\Python 2.3.4c1\Programming\Programs 
> (Complete)\Hexadecimal-Binary-Text.py", line 147, in ?
>     convertnum()    ##convert numbers to whatever
>   File "C:\Program Files\Python 2.3.4c1\Programming\Programs 
> (Complete)\Hexadecimal-Binary-Text.py", line 83, in convertnum
>     res += str(binary[char])
> UnboundLocalError: local variable 'res' referenced before assignment
> 



More information about the Tutor mailing list