Home > Backend Development > Python Tutorial > Why Do I Get an UnboundLocalError in Python?

Why Do I Get an UnboundLocalError in Python?

Linda Hamilton
Release: 2024-12-05 22:20:17
Original
525 people have browsed it

Why Do I Get an UnboundLocalError in Python?

UnboundLocalError: Understanding Unbound Variables in Python

In Python, an UnboundLocalError occurs when a local variable is referenced before it has been assigned a value. Unlike other programming languages, Python doesn't require explicit variable declarations. Instead, variables are bound to values when assigned.

One way to trigger an UnboundLocalError is by accessing an unassigned variable:

>>> foobar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foobar' is not defined
Copy after login

Another way is when an assignment operation fails to execute, such as within a conditional block:

def foo():
    if False:
        spam = 'eggs'
    print(spam)

>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in foo
UnboundLocalError: local variable 'spam' referenced before assignment
Copy after login

In Python, names are bound to values through various operations: assignment, function parameters, import statements, exception handlers, and context managers. When a name is bound in a function scope, it becomes a local variable. To access a global variable within a function, a global or nonlocal statement must be used (in Python 3).

For example, the following function attempts to access a global variable foo but fails because it's bound within the function scope:

foo = None
def bar():
    if False:
        foo = 'spam'
    print(foo)

>>> bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in bar
UnboundLocalError: local variable 'foo' referenced before assignment
Copy after login

However, using global foo fixes the issue:

foo = None
def bar():
    global foo
    if False:
        foo = 'spam'
    print(foo)

>>> bar()
None
Copy after login

Understanding the concept of variable binding is crucial to avoid UnboundLocalErrors in Python.

The above is the detailed content of Why Do I Get an UnboundLocalError in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template