Skip to content Skip to sidebar Skip to footer

Error When Assigning Local Variable With Same Name As A Global Variable

I am seeing an error when assigning either a global or an enclosing-function local to a local variable with the same name. The code below illustrates this issue, where f() runs fi

Solution 1:

The short answer is that, within g(), you need to declare

global a

if you want to be able to modify "a" from within a function and have this effect globally visible. However, in your case, the effect of using "a" within g() is to convert this variable name to refer to a local-scope variable, which then hides the global "a" which you're attempting to use on the righthand side of your assignment, triggering the exception. This is more fully explained here. There is also a Python FAQ which explains the rules that make f() work without the need for the "global a".


Post a Comment for "Error When Assigning Local Variable With Same Name As A Global Variable"