The following code raises an UnboundLocalError
:
def foo(): i = 0 def incr(): i += 1 incr() print(i) foo()
Is there a way to accomplish this?
Use nonlocal
statement
def foo(): i = 0 def incr(): nonlocal i i += 1 incr() print(i) foo()
For more information on this new statement added in python 3.x, go to https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With