You can use a global variable in other functions by declaring it as global in each function that assigns to it.
I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the global
keyword.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
globvar = 0 def set_globvar_to_one(): # Needed to modify global copy of globvar global globvar globvar = 1 def print_globvar(): # No need for global declaration to read value of globvar print(globvar) set_globvar_to_one() # Prints the output print_globvar() |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.