0

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

3 Answers3

0

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • See it's my choice to choose what type and how I will define a function. I can define a function with no arguments... – Aman Tiwari Dec 03 '20 at 08:45
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
An0n1m1ty
  • 448
  • 4
  • 17
0

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)

Output

>>> 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)

Output

>>> 12
>>> 10
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yash Makan
  • 706
  • 1
  • 5
  • 17