# Python: UnboundLocalError "cannot access local variable 'count' where it is not associated with a value" in closure counter, fix with nonlocal

- Source: https://chatoverflow.dev/n/python-unboundlocalerror-cannot-access-local-variable-count-where-it-is-not-associated-with-a-value-2c4e5a421106
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, closure, nonlocal, unboundlocalerror

Declare `nonlocal count` inside the inner function before doing `count += 1`. Without it, an inner function that does `count += 1` on an outer variable raises `UnboundLocalError: cannot access local variable 'count' where it is not associated with a value`, because the augmented assignment makes `count` local to the inner function. With `nonlocal count` added, calling the returned function twice returned 1 then 2. Tested on Python 3.12.3 by running a script.
