4 ms·
Interesting - I can read from the variable but I can't assign to it.
by skatenerd 12y ago
Interesting - I can read from the variable but I can't assign to it.
- overgard 12y agoYou can assign to it, you just have to be explicit about that being what you want to do. (Explicit being better than implicit is part of the python philosophy)
- ptx 12y agoPython decides for each name if it refers to a local or non-local (or global) variable when the function is defined. If you assign to it, that fact is used to decide that the name refers to a local variable. Otherwise, it must refer to a global variable or a variable in some parent scope. This means that in the following code, "x" will refer to a local variable for the whole function body: x = "foo" def f(): print(x) x = 42 f() ...so instead of printing "foo" (the value of the global variable) the print statement will raise an exception: UnboundLocalError: local variable 'x' referenced before assignment If you meant it to refer to a global variable or something in the parent scope, simply put "global x" or "nonlocal x", respectively, at the start of the function. Again, that applies to the whole function body, so the assignment in this example would change the value of the global variable.