My code
x = 10
def fun():
x = x + 2
print(x)
fun()
print(x)
And the output error
UnboundLocalError: local variable 'x' referenced before assignment
x = 10
def fun():
x = x + 2
print(x)
fun()
print(x)
UnboundLocalError: local variable 'x' referenced before assignment
You don't give x as the parameter to the function. That's why.
x = 10
def fun(x):
x = x + 2
print(x)
fun()
print(x)
Your variable x
, that you're trying modify in the function fun()
, is of global scope. Hence, you can't access it inside the function like that. However, you can use:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
Appending global x
, will allow the function to modify the variable x
which is in global scope.
You have to pass global x
in the def fun() as no variable named x is assigned in fun(). Here is the code:
x = 10
def fun():
global x
x = x + 2
print(x)
fun()
print(x)
>>> 12
>>> 12
OR
You can also simply pass an argument, but this makes a difference in the values of x:
x = 10
def fun(x):
x = x + 2
print(x)
fun(x)
print(x)
>>> 12
>>> 10