Scope question

Nitro nitro at
Mon Aug 6 15:06:58 CEST 2007


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

This gives an

UnboundLocalError: local variable 'y' referenced before assignment

If I change the function like this:

y = 0
def func():
     print y

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?


More information about the Python-list mailing list