Python has two areas (actually three), plus special rules for local local areas. These two areas are global, for module names, and local, for anything in a function. Everything that you assign to a function is automatically local, unless you declare it otherwise with the global statement in that function. If you use a name that is not assigned anywhere in the function, this is not a local name; Python will (lexically) look for nesting functions to find out if they have that name as a local name. If there are no nested functions or the name is not local in any of them, this name is considered global.
(The global namespace is also special because it is in fact both a global module namespace and an embedded namespace that is hidden in the builtins or __builtins__ module.)
In your case, you have three x variables: one in the module area (global), one in the counter function and one in the temp function, because += also an assignment operator, since the fact of the name assignment makes it local to the function, your operator += will try to use a local variable that has not yet been assigned, and this will raise an UnboundLocalError.
If you pointed to all three of these references x to refer to a global variable, you need to make global x both in the counter and temp functions. In Python 3.x (but not 2.x), there is a nonlocal declaration similar to global , which you can use to make temp variable assignment to counter , but leave global x alone.
Thomas wouters
source share