[Tutor] "local variable 'l1' referenced before assignment"
Alan Gauld
alan.gauld at btinternet.com
Sat Jun 28 10:05:34 CEST 2008
"Dick Moores" <rdm at rcblue.com> wrote
> I'm puzzled by the below error msg. If I change the line in a2()
> from
>
> l1 = [1,2,3]*100
This is not in a2() this is in the global namespace outside of a2.
a2() consists of a single assignment statement. And assignment
inside a function creates a local variable which in this case
masks the global variable. But the local variable assignment
uses the same variable which is not allowed so you get the
error message.
> Why? And why isn't that line a problem for a1()?
In a1 you don't assign so you never create a local variable
you use the global variable
> =========================================
> def a1():
> return l1.extend(l2)
No assignment, it returns the global value
> if __name__=='__main__':
> l1 = [1,2,3]*100
> t = Timer("a1()", "from __main__ import a1")
> def a2():
> l1 += l2
new local variable "created" but erroneously. Change to
def a2():
global I1
I1 += I2
return I1
See my tutor topic on namespaces for more on this theme.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list