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.
pis 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 pbefore using it.For more information on the
globalkeyword, see https://docs.python.org/3/reference/simple_stmts.html#global.