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,579
  • 8
  • 30
  • 52

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,453
  • 1
  • 16
  • 27
  • @Atinesh edited my answer to add additional informations, tell me if it remains unclear. – 3kt Jun 02 '16 at 07:50