0

I have a string called x and function called my_func. I want to add a string to the x, from my_func. I tried below code but it returns an error and says "UnboundLocalError: local variable 'x' referenced before assignment". How can I fix it?

x = ""
def my_func():
    x += "Hello World"
my_func()
print(x)
Zienz
  • 3
  • 2
  • 3
    You don't seem to call the function. If you did you'd get an UnboundLocalError exception. Read about local and global variables in the documentation – DarkKnight Aug 06 '22 at 11:30
  • Please update your question with the full error traceback. – quamrana Aug 06 '22 at 11:32
  • Related: https://stackoverflow.com/questions/53249829/python-keep-changes-on-a-variable-made-within-a-function – DialFrost Aug 06 '22 at 12:13

2 Answers2

0

Your variable x is local, it has to be inside the function for it to work:

x = ""
def my_func(x):
    x += "Hello World"
    return x
x = my_func(x)
x = my_func(x)
print(x)

gives:

Hello WorldHello World

The trick is to reassign x.

DialFrost
  • 1,610
  • 1
  • 8
  • 28
  • you should be returning x, `return x` instead of print. Still, your answer looks good :) – Niqua Aug 06 '22 at 11:29
  • @DialFrost OP wants to add (append) a string to *x*. This code does not do that. Add *print(x)* after the call to *my_func* and you'll see that nothing's happened to it – DarkKnight Aug 06 '22 at 11:32
  • @DialFrost That still won't modify the global variable *x*. Remember that strings are passed by value (not by reference) – DarkKnight Aug 06 '22 at 11:36
  • @DialFrost not really what i want to. Your code is like an illusion, it returns what i want to but it doesn't append it to the variable x so i can't repeat it – Zienz Aug 06 '22 at 11:57
  • @Zienz: You only need to do: `x = my_func(x)` to make the modification. – quamrana Aug 06 '22 at 12:12
  • Yes, I see. Unfortunately I can't up vote you again. :-( – quamrana Aug 06 '22 at 12:15
0

Yes, I know it should be inside the function but if i do that, it wouldn't work as i want it to. Because i am recalling the func multiple times and need it to keep adding strings to x variable. For example, i need belove code to output "Hello worldHello world" instead of "Hello world". Btw i know my english is bad, sorry about that

def my_func():
    my_func.x = ""
    my_func.x += "Hello world"
my_func()
my_func()
print(my_func.x)
Zienz
  • 3
  • 2