0 votes
in Python by
Explain the UnboundLocalError exception and how to avoid it?

1 Answer

0 votes
by

Answer:

Problem

Consider:

>>> x = 10
>>> def foo():
...     print(x)
...     x += 1

And the output:

>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment

Why am I getting an UnboundLocalError when the variable has a value?

When you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

In the example above you can access the outer scope variable by declaring it global:

>>> x = 10
>>> def foobar():
...     global x
...     print(x)
...     x += 1
>>> foobar()
10

Related questions

0 votes
asked Jan 3 in Python by DavidAnderson
+1 vote
asked Feb 14, 2021 in Python by SakshiSharma
...