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()
Asked By: Brandon Nadeau

||

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()
Answered By: Hai Vu

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)
Answered By: wim

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()
Answered By: user1763510
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.