Akshat Shekhar Akshat Shekhar - 1 year ago 62
Python Question

Python function global variables?

So I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)

x = somevalue

def func_A ():
global x
# do things to x
return x

def func_B():
# do things
return x


Does the
that the second function uses have the same value of the global copy of
uses and modifies? When calling the functions after definition, does order matter?

Answer Source

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.


global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download