I was wondering why i was getting this error for adding a letter to this string from a function.
local variable 'string' referenced before assignment
CODE
def update_string():
string+='d'
string='s'
update_string()
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.
There is nowhere for the old ‘string’ to come from in the local scope of your function, so python assumes you’re talking about the one from the outer scope.
Moreover, since strings are immutable the usual pattern is to create a new one and return it, so you might prefer to update your function interface to something more like:
And then you would use it instead like: