About the global keyword in python

python

Solution

The trick here is that local names are detected statically:

- As long as the name `x` is not assigned in the function, references to `x` resolve to the the global scope

- If the name `x` is assigned anywhere in the function, Python assumes that `x` is thus a local name everywhere in the function. As a consequence, the first line becomes an error because local name `x` is used before being assigned.

In other words: assigned name is treated as local everywhere in the function, not just after the point of assignment.

Problem

``` # coding: utf-8 def func(): print 'x is', x #x = 2 #if I add this line, there will be an error, why? print 'Changed local x to', x x = 50 func() print 'Value of x is', x ``` - I don't add the `global x` in func function, but it can still find `x` is 50, why? - When I add the `x=2` line in the func function, there will be an error (`UnboundLocalError: local variable 'x' referenced before assignment`), why?

Original source