Search code examples
pythongloballocal

Error when referencing a inside a function without using `global` keyword in python


Why does the following code raise an UnboundedLocalError:

n = 0
def foo():
    n = n + 1
    print(n)
foo()
foo()

Error:

Traceback (most recent call last):
  File "foo.py", line 5, in <module>
    foo()
  File "foo.py", line 3, in foo
    n = n + 1
UnboundLocalError: local variable 'n' referenced before assignment

While the following code works:

n = 0
def foo():
    print(n)
foo()
foo()

Output:

0
0

It seems to me that given the behavior of the second snippet, the first snippet should use the value of the global n to calculate n+1 and assign it to a new local n, and print it. Thus, I would expect the output to be two 1s. Why does this not happen?


Solution

  • As soon as you write n = ..., n becomes a local variable for the entire function scope. To make the name n refer to the global variable, you must use the global statement.

    In the second example, there is no assignment to n, so n is undefined. It's a free variable, and its value will be taken from the closest enclosing scope where n is defined.