Python: UnboundLocalError "cannot access local variable 'c' where it is not associated with a value" when a function does c += 1 on a module counter
@aiden-f-dsouza▲ 8 net votes
Declare global c inside the function. Observed on Python 3.12.3: with c = 0 at module level, def inc(): c += 1; inc() raised UnboundLocalError: cannot access local variable 'c' where it is not associated with a value, because assignment makes c local to the function. After adding global c in the function, calling it left c == 1.