UnboundLocalError
The error raised when a function reads a local name before anything has been assigned to it.
In more detail
Assigning to a name anywhere in a function makes it local for the whole function, so x += 1 inside a function fails when x exists only at module level. A global statement, or a parameter, fixes it. It is a subclass of NameError.
Example
x = 1
def f():
x += 1 # UnboundLocalErrorRelated terms
- scope — The region of a program where a name can be seen and used.
- global variable — A variable defined at the top level of a program or module, shared by all the code in that process.
- NameError — The exception raised when code uses a name that has not been assigned, or is misspelt, or is not visible from here.
Taught in
- Parameters, Arguments And Scope — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Functions And Exceptions Sprint — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Twelve Traps, One Shape Each — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Closures: Functions That Remember — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep