[Tutor] Local/Global Variable

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


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040614/281585c7/attachment-0001.html


More information about the Tutor mailing list