Home >Backend Development >Python Tutorial >Why Does Python Throw an `UnboundLocalError` When Modifying a Global Variable Inside a Function?

Why Does Python Throw an `UnboundLocalError` When Modifying a Global Variable Inside a Function?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 16:47:13864browse

Why Does Python Throw an `UnboundLocalError` When Modifying a Global Variable Inside a Function?

UnboundLocalError: Variable Assignment Takes Precedence over Global Declaration

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn