Python: local variable 'string' referenced before assignment
Question:
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()
Answers:
You are accessing global variable, need to declare it:
def update_string():
global string # <<< declare `string` as global variable.
string+='d'
string='s'
update_varibles()
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:
def update_string(str_in):
return str_in + 'd'
And then you would use it instead like:
my_string = update_string(my_string)
You can access the variable from the outer scope inside the function, but you can’t assign to it. So the following is a workaround without using global variables or inputs to the function:
def update_string():
updated=string+"d"
return updated
string="s"
string=update_string()
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()
You are accessing global variable, need to declare it:
def update_string():
global string # <<< declare `string` as global variable.
string+='d'
string='s'
update_varibles()
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:
def update_string(str_in):
return str_in + 'd'
And then you would use it instead like:
my_string = update_string(my_string)
You can access the variable from the outer scope inside the function, but you can’t assign to it. So the following is a workaround without using global variables or inputs to the function:
def update_string():
updated=string+"d"
return updated
string="s"
string=update_string()