Akshat Shekhar Akshat Shekhar - 6 months ago 12
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():
x=func_A()
# do things
return x

func_A()
func_B()


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

Answer

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.

E.g.

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.

Comments