Why does python think this is a local variable?

I have a global variable that I named Y_VAL, which is initialized with a value of 2.

Then I have a function called f () (for short) that uses Y_VAL.

def f():
    y = Y_VAL
    Y_VAL += 2

However, when I try to run my python code, it gives an error message:

UnboundLocalError: local variable 'Y_VAL' referenced before assignment

If you delete the last line Y_VAL += 2, it works fine.

Why does python think that Y_VAL is a local variable?

+5
source share
3 answers

There is no string in this function global Y_VAL.

Y_VAL , , , . , , , global Y_VAL.

:

, , .

+14

Python: . .

, global. global . , global , .

+1

, , , , . . , , , .

, "" , init (self), , . , .

0

All Articles