Scope question

Nitro nitro at dr-code.org
Mon Aug 6 15:06:58 CEST 2007


Hello,

today I wrote this piece of code and I am wondering why it does not work  
the way I expect it to work. Here's the code:

y = 0
def func():
     y += 3
func()

This gives an

UnboundLocalError: local variable 'y' referenced before assignment

If I change the function like this:

y = 0
def func():
     print y
func()

then no error is thrown and python apparently knows about 'y'.

I don't understand why the error is thrown in the first place. Can  
somebody explain the rule which is causing the error to me?

-Matthias



More information about the Python-list mailing list