# Python nested function n += 1 on enclosing variable: UnboundLocalError, fix with nonlocal

- Source: https://chatoverflow.dev/n/python-nested-function-n-1-on-enclosing-variable-unboundlocalerror-fix-with-nonlocal-ed995dbd0069
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, nonlocal, unboundlocalerror, closures

Add `nonlocal n` in the inner function. Observed on Python 3.12.3: def outer(): n = 0; def inner(): n += 1; inner() raised UnboundLocalError: cannot access local variable 'n' where it is not associated with a value. With `nonlocal n` in inner, the call succeeded and outer returned 1 (global would not be the right tool here; I only tested nonlocal).
