0

So here is the code that uses x inside a function.

x = 1
def f():
    y = x
    x = 2
    return x + y
print x
print f()
print x

but python is not going to look up the variable out of function scope , and it results in UnboundLocalError: local variable 'x' referenced before assignment . I am not trying to modify the value of global variable , i just want to use it when i do y=x.

On the other hand if i just use it in return statment , it works as expected:

x = 1
def f():
  return x
print x
print f()

Can some one explain it why?

Ijaz Ahmad
  • 11,198
  • 9
  • 53
  • 73
  • problem is not `y = x` but `y = x` with `x = 2` together. Remove one of them and this error disappears. ( but you may get different :) ) – furas Nov 18 '16 at 11:23
  • but `x = 2` is below `y=x` , so i mean python should deal with `y=x` first , assign 1 to y and then on the line `x=2` create a new local variable and assign a value 2 to it. isnt it? – Ijaz Ahmad Nov 18 '16 at 13:14

1 Answers1

2

you have to specify global x in your function if you want to modify your value, however it's not mandatory for just reading the value:

x = 1
def f():
    global x
    y = x
    x = 2
    return x + y
print x
print f()
print x

outputs

1
3
2
JMat
  • 752
  • 6
  • 14
  • i think i am not modifying the value. question updated – Ijaz Ahmad Nov 18 '16 at 11:14
  • `y = x` , is not modifying `x` , so why i need a `global` keyword here – Ijaz Ahmad Nov 18 '16 at 11:16
  • @IjazKhan `y = x` is not but `x = 2` is. – JMat Nov 18 '16 at 11:19
  • but `x=2` , is meant to assign a new local variable assignment , python will look first at local scope in this case. since the the line `y=x` is above that line , in that case python should look at global scope and bring the value 1 to y – Ijaz Ahmad Nov 18 '16 at 13:12
  • @IjazKhan without `global`, python sees `y=x` so it instantiate `y` based on the global `x` since reading global variable is fine. however `x=1` tries to modify the global variable `x` which is forbidden without a `global x`. The idea behind is that, reading a global variable is harmless so python let's you do it without precaution. However modifying a global variable can have unexpected consequences so python requires you to explicitly say "I want to use the global variable `x` and be able to modify it" – JMat Nov 18 '16 at 13:40
  • no , but when i do `x=2` on that i line i mean to create a local variable x , and on `y=x` i mean that python will lookup global variable since it is just a read of global variable. – Ijaz Ahmad Nov 18 '16 at 14:28