LEGB rule, totally confused ...
siona at chiark.greenend.org.uk
Tue Aug 14 18:46:03 CEST 2007
stef mientki <stef.mientki at gmail.com> wrote:
> def Run ():
> print X <=== UnboundLocalError: local variable
> 'X' referenced before assignment
> X = X + 1
>Why do I get the error ?
>Printing isn't assigning anything or am I missing something.
>Now if I remove "X = X + 1" I don't get an error ???
Several people have already explained the scoping rules acting
here, but let's just look at how that error message is telling
you everything you need to know to fix the problem.
"local variable 'X' referenced before assignment"
"local variable 'X'" immediately tells you that the 'X' in
question is not your global 'X'.
"referenced before assignment": well, 'print X' is surely a
reference to 'X', and 'X = X + 1' is an assignment to it,
and 'print X' appears before 'X = X + 1'. That this is the
key you have confirmed experimentally.
The question to ask here is "Why does Python think 'X' is
local?" Everything else is answered by the error message.
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
More information about the Python-list