0

I have lots of functions, they all edit some variable but I want each to edit the previously edited variable (by the prior function):

text = "a"    
def a():
        text + " hi"
        print(text)
def b():
       text + " there"
       print(text)
def main():
      a()
      b()
main()

^So when running main I want this to appear:

>>a hi
>>a hi there

I've tried global but I can't seem get it working

0

2 Answers 2

1

Even when using global, you still have to re-assign a new value to the global variable - in your case text. text + " hi" simply creates a new string and throws it away. Use global text and then do text = 'text' + <string> as well:

text = "a"    

def a():
    global text
    text = text + " hi"
    print(text)

def b():
    global text
    text = text + " there"
    print(text)

def main():
      a()
      b()
main()

The above now outputs:

a hi
a hi there
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. Out of interest, if text ="a" was in a separate function and not outside them all, how would one call it in a different function?
You'd still use global. Here's a simple example of what I mean @GskgskgxBczkgxlhx. Also, please don't forget to mark my answer if it helped you :-)
0

use global in order to reassign text variable

text = "a"    
def a():
    global text
    text += " hi"
    print(text)
def b():
    global text
    text += " there"
    print(text)
def main():
    a()
    b()
main()

result with

a hi
a hi there

1 Comment

ofcourse, sorry i'd used online repl for testing and it paste it weird

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.