Sean Givan schrieb:
> Hi.  I'm new to Python

welcome

> ago.  I was doing some experiments with nested functions, and ran into 
> something strange.
> 
> This code:
> 
> def outer():
>     val = 10
>     def inner():
>         print val
>     inner()
> 
> outer()
> 
> ...prints out the value '10', which is what I was expecting.
> 
> But this code..
> 
> def outer():
>     val = 10
>     def inner():
>         print val
>         val = 20
>     inner()
>     print val
> 
> outer()
> 
> ...I expected to print '10', then '20', but instead got an error:
> 
>   print val
> UnboundLocalError: local variable 'val' referenced before assignment.
> 
> I'm thinking this is some bug where the interpreter is getting ahead of 
> itself, spotting the 'val = 20' line and warning me about something that 

just a little carefull thought
if something that basic should really be a bug
how many thousand people would discover it daily?

> doesn't need warning.  Or am I doing something wrong?

yes, you can't modify it
you can do it for global namespace or local
but not inbetween

val = 0
def outer():
        val = 10
        def inner():
                global val
                val = 30
        inner()
        print val
outer()
10              # outer val is not changed
print val       # global is modified
30

hth, Daniel

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to