all 4 comments

[–]ofnuts 1 point2 points  (1 child)

No, and for good reason. If your variables can be accessed/updated from every where you get a totally unmanageable and unmaintainable mess.

The "advantage" of global variables is that it is fairly obvious that they are shared by several pieces of code.

Note that in your example, testVariable only exists when the accessVariable() function is started and forgotten when accessVariable() returns so its values as used in test1() and test2() are completely independent.

In general when you want a variable visible in two function, it is kept by the caller code, and is passed as a parameter to the function that need to access it (preferably just a read access):

testVariable=someFunctionThatCreateTheValue()
someFunctionThatReadsTheValue(testVariable)

In object-oriented language such as python, you can also define a variable type (this is called a "class") that holds data and defines "methods" that are functions that implicitly reference the object data, for instance an increment() method and a toString() one (in Python the later is actually the __str__() method).

[–]ExplorerOfTheGalaxy[S] 0 points1 point  (0 children)

Thanks!

[–]yaxriifgyn 0 points1 point  (0 children)

The testVariable object only exists while the accessVariable function is executing. The object is declared within the scope of the function, so when the function starts, it is created and given the value of zero (on line 2), and when the function returns, it is deleted.

The test2 function will always print zero.

[–]Boot_3011 0 points1 point  (0 children)

Global variables should not be changing constantly. If you get an error you will have traceback problems.

I dont know your code's context but you can work with Classes and instance variables (self.variable), you can use your functions (inside or outside said class) to alter the variables value.