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

PythonGlobal Variables

Python Problem Overview


In Python, I'm getting the following error:

UnboundLocalError: local variable 'total' referenced before assignment

At the start of the file (before the function where the error comes from), I declare total using the global keyword. Then, in the body of the program, before the function that uses total is called, I assign it to 0. I've tried setting it to 0 in various places (including the top of the file, just after it is declared), but I can't get it to work.

Does anyone see what I'm doing wrong?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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 won't

    inner()

Solution 3 - Python

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

>>>'info'

problem ended

Solution 4 - Python

I want to mention that you can do like this for the function scope

def main()

  self.x = 0

  def increment():
    self.x += 1
  
  for i in range(5):
     increment()
  
  print(self.x)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremyView Question on Stackoverflow
Solution 1 - PythonstefanBView Answer on Stackoverflow
Solution 2 - PythonzinkingView Answer on Stackoverflow
Solution 3 - PythonninjaView Answer on Stackoverflow
Solution 4 - PythonGennadiy RyabkinView Answer on Stackoverflow