python – Why do I get a referenced before assignment error when assigning to a global variable in a function?

python – Why do I get a referenced before assignment error when assigning to a global variable in a function?

I think you are using global incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar.

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

See this example:

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == __main__:
    main()

Because doA() does not modify the global total the output is 1 not 11.

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these wont

    inner()

python – Why do I get a referenced before assignment error when assigning to a global variable in a function?

def inside():
   global var
   var = info
inside()
print(var)

>>>info

problem ended

Leave a Reply

Your email address will not be published.