0

I'm trying to write a simple code that uses a global variable. I'm getting the following error

UnboundLocalError: local variable 'x' referenced before assignment

global x

def update():    
    x = x + 1

x = 0
update()
print(x)
Atinesh
  • 1,790
  • 9
  • 36
  • 57

1 Answers1

0

Your error occurred because in the function update, you are trying to edit a variable (x) that is not defined, at least not locally. The global keyword should be inside the function, and hence tell that the x you are speaking about is the one defined outside of the function (therefore globally defined) :

def update():
    global x
    x = x + 1

x = 0
update()
print(x)

This would output 1, as expected.

You can take a look at this well detailed answer regarding the use of the global keyword.

Community
  • 1
  • 1
3kt
  • 2,543
  • 1
  • 17
  • 29
  • @Atinesh edited my answer to add additional informations, tell me if it remains unclear. – 3kt Jun 02 '16 at 07:50