Namespace and Scope

18 Views Asked by At

The below code does not run: It gives " UnboundLocalError: local variable 'p' referenced before assignment"

p="hello"
def z():
    if p == "hello":
        p="2"
        print(p)
z()

But this code works, i am confused! in both cases i am assigning a variable inside a function.That should be local right? The above code should also print 2 then.

p="hello"
def z():
    p="2"
    print(p)
z()

Output : "2"

and this also works

p="hello"
def z():
    if p == "hello":
        x="2"
        print(x)
z()

Output = 2

I am not expecting the local variable 'p' referenced before assignmen error.

1

There are 1 best solutions below

8
thom747 On

p is a global variable because it was defined in the global scope.

To assign to a global variable from a non-global scope, such as in your function, you need to declare its usage with global p before using it.

For more information on the global keyword, see https://docs.python.org/3/reference/simple_stmts.html#global.