-1

I have a little python application, and declared at the top of the application a string called lastMsg, in a function, this string should be changed, but instead of changing the existing string, it creates a new string, how can I change the old string?

2
  • 4
    How about sharing your code? Commented Sep 8, 2017 at 10:13
  • Can you not just assign the return value of the function to the variable? using globals is bad practice. Commented Sep 8, 2017 at 10:15

2 Answers 2

1

If I guessed correctly what you are trying to do (do share some code to further explain your answer):

You need to use the global keyword to specify you want to change the global variable.

myVar = "1"

def myFun():
    global myVar
    myVar = "2"

print(myVar)
myFun()
print(myVar)

Should print:

1
2
Sign up to request clarification or add additional context in comments.

Comments

0

It's not quite clear what you're asking.

I think you mean this:

lastMsg = "some string"

def a_function():
    lastMsg = "new value"

If so, you can change it using the global keyword:

lastMsg = "some string"

def a_function():
    global lastMsg

    lastMsg = "new value"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.