Home >Backend Development >Python Tutorial >Why Does `counter = 1` Inside a Function Cause an `UnboundLocalError` in Python?
UnboundLocalError in Closures: An Analysis
An UnboundLocalError occurs when a variable used within a function's code is not defined locally, globally, or as part of a nonlocal block. Consider the following code:
counter = 0 def increment(): counter += 1 increment()
Running this code will result in an UnboundLocalError. Why does this occur?
Understanding Python's Variable Scope
Python dynamically determines variable scope based on assignment. If a variable is assigned within a function, it is considered local to that function. In our example, the assignment counter = 1 within increment() implicitly defines counter as local to that function.
Local vs. Global Variables
Python distinguishes between local and global variables. Global variables are declared at the module level and are accessible throughout the program. Local variables, on the other hand, are created within functions and only exist within those functions.
In our case, counter is not defined globally. The error occurs because Python tries to read the value of counter from the local scope of increment() before it has been assigned, hence the UnboundLocalError.
Resolving the Error
To resolve this error, you can do one of the following:
The above is the detailed content of Why Does `counter = 1` Inside a Function Cause an `UnboundLocalError` in Python?. For more information, please follow other related articles on the PHP Chinese website!