Search code examples
pythoncomputer-science

Error Code: UnboundLocalError: local variable referenced before assignment


It seems that many get this error but each situation is different.

My code:

i = 0

def sort(a):

    b = len(a)

    if(i == b):
        print (a)

    elif(b == 0):
        print ('Error. No value detected...')

    elif(b == 1):
        print (a)

    elif(a[i]>a[i+1]):
        a[i], a[i+1] = a[i+1], a[i]

        i = i + 1
        print(a)
        sort(a)

Error Code:

Traceback (most recent call last):
 File "<string>", line 301, in runcode
 File "<interactive input>", line 1, in <module>
 File "(File location, you don't need to know....)", line 8, in sort
   if(i == b):
 UnboundLocalError: local variable 'i' referenced before assignment

I am not sure what this error means or what is wrong.


Solution

  • Your variable i is defined at the global (module) level. See Short Description of the Scoping Rules? for info the order in which python looks for your variable. If you only try to reference the variable from within your function, then you will not get the error:

    i = 0
    
    def foo():
        print i
    
    foo()
    

    Since there is no local variable i, the global variable is found and used. But if you assign to i in your function, then a local variable is created:

    i = 0
    
    def foo():
        i = 1
        print i
    
    foo()
    print i
    

    Note that the global variable is unchanged. In your case you include the line i = i + 1, thus a local variable is created. But you attempt to reference this variable before it is assigned any value. This illustrates the error you are getting:

    i = 0
    
    def foo():
        print i
        i = 1
    
    foo()
    

    Either declare global i within your function, to tell python to use the global variable rather than creating a local one, or rewrite your code completely (since it does not perform as I suspect you think it does)