Home >Backend Development >Python Tutorial >Why Does `counter = 1` Inside a Python Function Cause an `UnboundLocalError`?
UnboundLocalError Explained in Python Closures
The situation described in the question revolves around a fundamental concept in Python known as variable scope. Unlike languages with explicit variable declarations, Python determines variable scope based on assignment.
Consider the following code:
counter = 0 def increment(): counter += 1 increment()
This code raises an UnboundLocalError. Why?
In Python, an assignment within a function marks the variable as local to that function. The line counter = 1 in the increment() function implies that counter is a local variable. However, this line attempts to access the local variable before it is assigned, leading to the UnboundLocalError.
To circumvent this issue, you have several options:
counter = 0 def increment(): global counter counter += 1
def outer(): counter = 0 def inner(): nonlocal counter counter += 1
By utilizing these techniques, you can correctly manipulate local and global variables within closures, avoiding unnecessary errors.
The above is the detailed content of Why Does `counter = 1` Inside a Python Function Cause an `UnboundLocalError`?. For more information, please follow other related articles on the PHP Chinese website!