If you run the code below, you will receive UnboundLocalError
. What's wrong?
counter = 0
def increment():
counter += 1
increment()
The concept of variable declaration does not exist in Python. Therefore, Python determines the range of use of a variable with the following rules: If a variable is used in a function, it is considered a local variable. [1] Accordingly, the following
counter += 1
treats counter
as a regional variable for the function increment()
. Therefore, running this syntax will attempt to read the value of the local variable before it is assigned counter
, which will cause UnboundLocalError
.
If you want to use counter
as a global variable, you can use the global
keyword. Also, for Python 3.x, use if the function
increment()
is used as the built-in function and counter
is the regional variable (including increment()
function).
© 2025 OneMinuteCode. All rights reserved.