[Tutor] learning nested functions
Dave Angel
davea at davea.name
Wed Jul 10 13:52:48 CEST 2013
On 07/08/2013 02:26 AM, Tim Hanson wrote:
> In the first Lutz book, I am learning about nested functions.
>
> Here's the book's example demonstrating global scope:
>>>> def f1():
> x=88
> def f2():
> print(x)
> f2()
>
>
>>>> f1()
> 88
>
But that's not global scope, it's non-local scope. Global would be if
you were referencing a symbol defined at top-level.
> No problem so far. I made a change and ran it again:
>
>>>> def f1():
> x=88
> def f2():
> print(x)
> x=99
> print(x)
> f2()
>
>
>>>> f1()
> Traceback (most recent call last):
> File "<pyshell#11>", line 1, in <module>
> f1()
> File "<pyshell#10>", line 7, in f1
> f2()
> File "<pyshell#10>", line 4, in f2
> 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?
As Hugo says, a function is compiled into a single entity, and within
that entity, a given name is either local or not. It's decided by the
presence (anywhere in the function) of an assignment, or a with
statement, or maybe other name-binding statements.
--
DaveA
More information about the Tutor
mailing list