102

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?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Jeremy
  • 2,826
  • 7
  • 29
  • 25
  • 5
    Are you declaring global in the function? – Nikhil May 13 '09 at 00:10
  • 2
    Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – Tomerikoo Feb 10 '21 at 20:31

4 Answers4

200

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.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
stefanB
  • 77,323
  • 27
  • 116
  • 141
  • 37
    It might be worth nothing that you only need the "global" keyword if you assign to the global variable within a local scope. So in your example, the global declaration is not required in checkTotal(). – Greg Hewgill May 13 '09 at 00:31
  • 1
    Comprehensive answer, and a well-sussed analysis of the essential misunderstanding behind the question. – Jarret Hardie May 13 '09 at 00:40
  • 3
    I meant it might be worth *noting* of course! Still can't edit comments without delete-readd. :( – Greg Hewgill May 13 '09 at 00:49
  • when declaring a global variable, I had to assign a value to it (I did `glob_val=None`, IOW, I wasn't able to declare it without a value assignment – amphibient Oct 21 '16 at 17:07
7

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()
mic
  • 1,190
  • 1
  • 17
  • 29
zinking
  • 5,561
  • 5
  • 49
  • 81
1

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)
Henadzi Rabkin
  • 6,834
  • 3
  • 32
  • 39
-2
def inside():
   global var
   var = 'info'
inside()
print(var)

>>>'info'

problem ended

ninja
  • 1
  • 2
    It would be helpful to explain how your code works by a simple explanation or a comment – Anurag A S Oct 01 '20 at 14:15
  • The accepted answer seems to have covered the usage of `global` already. – General Grievance Oct 01 '20 at 17:16
  • This simply repeats what the accepted answer says, but as Anurag AS mentions, there is no explanation. And as General Grievance says, if the accepted answer already covers the usage of global, then why bother posting an unexplained bit of code that adds nothing to the conversation? – Mike S Oct 07 '22 at 19:49