LEGB rule, totally confused ...
stef.mientki at gmail.com
Tue Aug 14 19:39:02 CEST 2007
Sion Arrowsmith wrote:
> 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.
Thanks guys, I beginning to see the light again,
and if X is mutual the story is completely different,
I still have to get used to these differences.
More information about the Python-list