Python Forum
Global Variable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Global Variable (/thread-9373.html)



Global Variable - jarrod0987 - Apr-05-2018

Is it possible to declare a global string outside of the main function and then modify it later from inside the main function?
If so, how please?

Thanks.


RE: Global Variable - Larz60+ - Apr-05-2018

Therein lies the evil of global variables.
The answer to your question is yes and yes.

Consider the following,
The program will eventually fail precisely because you are allowed to change a global variable anywhere
MyGlobal = 17

def function_1(n):
    MyGlobal += n

def function_2():
    global MyGlobal
    print('MyGlobal is {}'.format(MyGlobal))

def function_3():
    global MyGlobal
    MyGlobal = str(MyGlobal)

def function_4():
    global MyGlobal
    for n in range(5):
        MyGlobal += n
        function_2()

def main():
    function_4()
    function_3()
    function_4()

if __name__ == '__main__':
    main()



RE: Global Variable - Gribouillis - Apr-05-2018

There are alternatives to the global statement. One of them is to use a class
class Aah:
    mystring = 'spam'
    otherstring = 'ham'
    
def main():
    print(Aah.mystring)
    Aah.mystring = 'eggs'
    print(Aah.mystring)
    
if __name__ == '__main__':
    main()
Output:
spam eggs



RE: Global Variable - ljmetzger - Apr-05-2018

Excellent examples @Larz60+ and @Gribouillis. Thank you.

Whether you are modifying a global variable or a class variable or a local variable you always have to know what your are doing and certain constructions don't mix in Python:
s = 'Hello'
s = s + '3'    #Works OK - concatenating two strings
s = s + 3      #Traceback error - mixing a string and an integer
Lewis


RE: Global Variable - jarrod0987 - Apr-06-2018

I have to learn more about this class thing. Just have not got that advanced yet. I like what it does though. Reminds me of a database.