Apr-05-2018, 12:22 AM
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.
If so, how please?
Thanks.
Global Variable
|
Apr-05-2018, 12:22 AM
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.
Apr-05-2018, 02:43 AM
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()
Apr-05-2018, 05:09 AM
(This post was last modified: Apr-05-2018, 05:10 AM by Gribouillis.)
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()
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 integerLewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Apr-06-2018, 03:09 AM
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.
|
|