Home > Enterprise >  How to add a string to another from a function
How to add a string to another from a function

Time:08-07

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)

CodePudding user response:

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.

CodePudding user response:

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)
  • Related