Python scope: “UnboundLocalError: local variable ‘c’ referenced before assignment” [duplicate]

Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the global statement:

def g(n):
    global c
    c = c + n

This is one of the quirky areas of Python that has never really sat well with me.

Leave a Comment