Possible Duplicate:
Modify the function variables frominner function in python
Say I have this python code
def f():
x=2
def y():
x+=3
y()
this raises:
UnboundLocalError: local variable 'x' referenced before assignment
So, how do I “modify” local variable 'x' from the inner function? Defining x as a global in the inner function also raised an error.
You can use
nonlocalstatement in Python 3:In Python 2 you need to declare the variable as an attribute of the outer function to achieve the same.
or using we can also use a
dictionaryor alist: