[Tutor] learning nested functions

Alan Gauld alan.gauld at btinternet.com
Wed Jul 10 19:39:28 CEST 2013


On 08/07/13 07:26, Tim Hanson wrote:
> In  the first Lutz book, I am learning about nested functions.

>>>> def f1():
> 	x=88
> 	def f2():
> 		print(x)
> 		x=99
> 		print(x)
> 	f2()
>
> 	
>>>> f1()
> Traceback (most recent call last):
>      print(x)
> UnboundLocalError: local variable 'x' referenced before assignment
>
> This doesn't work.  To my mind,in f2() I first print(x) then assign a variable
> with the same name in the local scope, then print the changed x.  Why doesn't
> this work?

Hugo and Dave have given a technical answer. Here's a less technical one 
(or maybe just a different one!).

Python does not execute your program line by line. It reads your program 
and builds up an internal structure of executable code and data.
In your case it sees that the function f2 has a local variable x in it 
so it assigns that x to that function object in its internal structure. 
When you then execute f2 it uses the local x throughout, but because you 
try to print x before assigning it you get an error.

If you want to use the "global" x you would need to declare it global 
(although your x is not strictly global - its just not local!). but that 
then prevents your assignment from creating a local x. In other words 
Python doesn't want you creating both local and global references in the 
same scope. Use a different name for your local variable.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list