0

On python 3.6,

Code 1:

x="glob"
def reg(x):
    print(x)
    x="loc"
    print(x)
reg(x)

Output:

glob loc

Code 2:

x="glob"
def reg():
    print(x)
    x="loc"
    print(x)
reg()

Output:

Traceback (most recent call last):
  File "D:\Projects\Python\abc.py", line 6, in <module>
    reg()
  File "D:\Projects\Python\abc.py", line 3, in reg
    print(x)
UnboundLocalError: local variable 'x' referenced before assignment

Why does this happen? What's the difference if I'm not passing a global variable to a function?? Shouldn't it be accessible to all the functions?

  • 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) – steviestickman Mar 01 '20 at 17:49

3 Answers3

0

You can visit https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html. There is an example about your issue.

UncleBob
  • 41
  • 10
0

You should user global.
Code 2

x="glob"
def reg():
    global x
    print(x)
    x="loc"
    print(x)
reg()
krishna
  • 1,029
  • 6
  • 12
0

The variable scope of inside and outside of function is different.
Inside of function definition, it has own scope when you assign new variables.
If you intend to reassign global variable, you should use global statement.

global x

This statement mean

When I assign variable in this function scope, it is not function scope but global scope

Please note that it is only about assigning, so you don't need to global statement to use global variables.
In addition, in most case, reassigning global variable is not a good idea, Since it makes your code complicated. There are so many alternatives of it.
But still you want to do this, you can:

x = "glob"
def reg():
    global x

    print(x)
    x = "loc"
    print(x)
reg()

And about the first example,
Reassigning argument in function does not affect outside of function.

Boseong Choi
  • 2,566
  • 9
  • 22