0

I encounter no problems running this code:

x = 1

def func():
    print(x + 1)

func()
2

But when I run this:

x = 1

def func():
    try:
        x += 1
    except:
        pass
    print(x + 1)

func()

An error pops:

UnboundLocalError: cannot access local variable 'x' where it is not associated with a value

I am not asking if I can modify global variables in functions or not. I used try-except keywords to avoid that error. After python caught the exception, I thought nothing would change and print(x + 1) would work like the first code. So what changed in the scope during the try-except part that x is no longer accessible?

UpTheIrons
  • 73
  • 1
  • 6
  • If you want to assign a new value to a global variable within a function, you must add `global x` as the first statement of the function. Otherwise, as you see, Python assumes you didn't really want to screw up a global. BTW, globals are evil. You should try to avoid them. – Tim Roberts Nov 22 '22 at 21:38
  • @TimRoberts I know. That's why I used the try-except keywords. I want to know what happens after 'except: pass' that x is no longer accessible inside the function. – UpTheIrons Nov 22 '22 at 21:40
  • it makes `x` **local**, which causes it to raise an exception, and the assignment to `x` never completes, so when you try to print `x + 1`, the variable is not defined – juanpa.arrivillaga Nov 22 '22 at 21:46
  • @UpTheIrons *the same reason* it wasn't accessible inside the `try: ... `block – juanpa.arrivillaga Nov 22 '22 at 21:46
  • Right. The MERE FACT that you have `x += 1` in your function makes the name `x` a local throughout the entire function. Python will no longer look for a global. – Tim Roberts Nov 22 '22 at 21:46
  • @TimRoberts Thank you. That was the answer I was looking for. – UpTheIrons Nov 22 '22 at 22:00

1 Answers1

0

The first example works because the function does not assign to the x variable; it only reads the variable.

The second example fails because if a function assigns to a variable then it is assumed to be a local variable, even if there is a global variable of the same name.

If you want to use the global variable in the function, put global x at the top of the function.

John Gordon
  • 29,573
  • 7
  • 33
  • 58