res = ' '
def paper_doll(text):
for i in text:
res = res+i+i+i
return res
paper_doll('Hello')
Error:
UnboundLocalError: local variable 'res' referenced before assignment
res = ' '
def paper_doll(text):
for i in text:
res = res+i+i+i
return res
paper_doll('Hello')
Error:
UnboundLocalError: local variable 'res' referenced before assignment
Although res is defined at the module level as a global variable, the fact that res is used as an assignee of an assignment statement in the paper_doll function makes the Python compiler mark it as a local variable within the scope of the paper_doll function block, so when it evaluates res+i+i+i during the first iteration of the for loop, it finds res uninitialized as res is not yet assigned with a value at that point.
As it is generally discouraged to change the value of a global variable from within a function, you should instead name res in the paper_doll function something else, and initialize it with the global variable res:
res = ' '
def paper_doll(text):
r = res
for i in text:
r = r+i+i+i
return r
res is a global variable and can be accessed but not modified without explicitly specifying global within the modifying function.
Or, simpler solution, define res within the function:
def paper_doll(text):
res = ' ' # or global res
for i in text:
res = res+i+i+i
return res
paper_doll('Hello')
Either way, outputs:
HHHeeellllllooo
Two possible solutions.
1: Tell the function paper_doll that the res variable you are planning to use inside the function is a global variable by writing global res inside the function like so.
res = ' '
def paper_doll(text):
global res
for i in text:
res = res+i+i+i
return res
print(paper_doll('Hello'))
#HHHeeellllllooo
Note that this might be a bad solution, because if you use this res variable somewhere else, you might not get the desired value since it is modified by someone else, e.g func already modified res for you changing the global variable, now when you use it in paper_doll you will get an unexpected result
res = ' '
def func():
global res
res = 'abcd'
def paper_doll(text):
global res
for i in text:
res = res+i+i+i
return res
func()
print(paper_doll('Hello'))
#abcdHHHeeellllllooo
res=0 inside the function and return it. You can still use res outside the function.
Here the local res was updated correctly, and the global res as well, and both didn't affect each otherres = ' '
def func():
global res
res = 'abcd'
def paper_doll(text):
res = ''
for i in text:
res = res+i+i+i
return res
func()
print(paper_doll('Hello'))
print(res)
#HHHeeellllllooo
#abcd