Home >Backend Development >Python Tutorial >Why Does My Python Code Throw an 'UnboundLocalError' When Accessing a Global Variable Within a Function?

Why Does My Python Code Throw an 'UnboundLocalError' When Accessing a Global Variable Within a Function?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 03:35:14801browse

Why Does My Python Code Throw an

Unbound Local Error: Local Variable 'c' Shadowing Global Scope

In Python, understanding the assignment rules for variables within functions is crucial to prevent potential errors. When facing an "UnboundLocalError," it's essential to investigate whether a variable assigned in a function is attempting to overshadow a global variable.

Consider the following code:

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

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

When executing this code, you will encounter an error stemming from the line "print(c)." The error message typically indicates that there is no "c" variable assigned within the local scope of the test() function.

To resolve this error, you need to understand that Python treats variables in functions differently based on where they are assigned. If you attempt to assign a value to a variable within a function, it becomes a local variable. However, in this code, you intend for "c" to remain global.

To declare that the "c" variable within the test() function references the global variable "c," you must explicitly use the "global" keyword at the start of the function:

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

By adding "global c," Python recognizes that you intend to work with the global "c" variable and not a local one. This allows you to print and modify the global "c" variable as expected.

As a newer feature introduced in Python 3, you can use "nonlocal c" instead of "global c" to refer to the nearest enclosing function scope that possesses a "c" variable. However, it's worth noting that using "nonlocal" is generally less common in everyday Python coding.

The above is the detailed content of Why Does My Python Code Throw an 'UnboundLocalError' When Accessing a Global Variable Within 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