Home >Backend Development >Python Tutorial >Why Does Reassigning a Variable in a Python Function Cause an UnboundLocalError?

Why Does Reassigning a Variable in a Python Function Cause an UnboundLocalError?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 03:14:09868browse

Why Does Reassigning a Variable in a Python Function Cause an UnboundLocalError?

Understanding UnboundLocalError when Reassigning a Variable within a Function

When a variable is defined outside a function, it is considered a global variable and is accessible within the function. However, if a variable is redefined within a function, it becomes a local variable and takes precedence over the global variable. This can lead to the error "UnboundLocalError" when trying to access the global variable by the same name.

In the example provided:

a, b, c = (1, 2, 3)

def test():
    print(a)
    print(b)
    print(c)
    c += 1

When this code is executed, the variables a, b, and c are defined globally. Within the test function, the lines print(a), print(b), and print(c) successfully print the values of the global variables.

However, when the line c = 1 is uncommented, it tries to reassign the value of c within the test function. This creates a new local variable c and assigns the value 4 to it. Consequently, when the line print(c) is executed, it refers to the local variable c and not the global variable c. Since the local variable c has not been assigned a value before it is referenced, the error "UnboundLocalError" is raised.

To avoid this error, you can use the global keyword before the variable name within the function to explicitly indicate that you want to access the global variable. For instance, the code below will work correctly:

a, b, c = (1, 2, 3)

def test():
    global c
    print(a)
    print(b)
    print(c)
    c += 1

In this case, when the test function is executed, the global c statement ensures that the variable c in the function refers to the global variable c and not a local variable. Therefore, the print(c) line will print the correct value of the global variable c.

The above is the detailed content of Why Does Reassigning a Variable in a Python Function Cause an UnboundLocalError?. 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