What am I doing wrong here?
counter = 0
def increment():
counter += 1
increment()
The above code throws an UnboundLocalError.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python doesn’t have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.[1] Thus, the line
implicitly makes
counterlocal toincrement(). Trying to execute this line, though, will try to read the value of the local variablecounterbefore it is assigned, resulting in anUnboundLocalError.[2]If
counteris a global variable, theglobalkeyword will help. Ifincrement()is a local function andcountera local variable, you can usenonlocalin Python 3.x.