When encountering an UnboundLocalError in Python, it's crucial to understand the precedence of variable assignments over global declarations. Let's delve into the specifics using the provided code:
a, b, c = (1, 2, 3) def test(): print(a) print(b) print(c) c += 1 test()
Before exploring the error, let's address the successful prints of 'a' and 'b'. For these variables, there is no assignment within the 'test()' function, so Python treats them as global variables and retrieves their values from the outer scope.
However, when assigning a value to 'c' within the function ('c = 1'), Python creates a local variable named 'c'. This local variable overshadows the global 'c', and any subsequent reference to 'c' within the function will refer to the local version. Therefore, when the line 'print(c)' is executed, it attempts to print the unassigned local variable, resulting in the 'UnboundLocalError'.
To address this issue, one can explicitly declare the use of the global 'c' variable within the 'test()' function by adding 'global c' as the first line. Alternatively, in Python 3, 'nonlocal c' can be used to access the nearest enclosing function scope that contains a variable named 'c'.
The above is the detailed content of Why Does Python Throw an `UnboundLocalError` When Modifying a Global Variable Inside a Function?. For more information, please follow other related articles on the PHP Chinese website!