0

I have two pieces of code:

def g(y):
  print(x)
x = 5 
g(x)

and

def h(y):
  x = x + 1
x = 5
h(x)

The first piece of code works perfectly fine printing '5' while the second piece returns:

UnboundLocalError: local variable 'x' referenced before assignment

What does this actually mean? Is it trying to say that it tried to evaluate the line x = x + 1 before it evaluates the line x=5? If that is so, why has the first piece of code not generated any error? It similarly had to evaluate the line print(x) before x was assigned a value.

I think I might have an misunderstanding how functions are called. But I do not know what it is that I got wrong.

Taenyfan
  • 13
  • 1
  • 4
  • This seems to be a duplicate of https://stackoverflow.com/questions/48368402/error-when-assigning-local-variable-with-same-name-as-a-global-variable/48368450#48368450. – rwp Jan 22 '18 at 20:01

2 Answers2

0
# first block: read of global variable. 
def g(y):
  print(x)
x = 5 
g(x)

# second block: create new variable `x` (not global) and trying to assign new value to it based on on this new var that is not yet initialized.
def h(y):
  x = x + 1
x = 5
h(x)

If you want to use global you need to specify that explicitly with global keyword:

def h(y):
  global x
  x = x + 1
x = 5
h(x)
aiven
  • 3,775
  • 3
  • 27
  • 52
0

Just as Aiven said, or you can modify the code like this:

def h(y):
   x = 9
   x = x + 1
   print(x) #local x
x = 5
h(x)
print(x) #global x
Eqzt111
  • 487
  • 6
  • 17