0 votes
1 view
in Python by (28.1k points)

How can I create or use a global variable in a function?

If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?

2 Answers

0 votes
by (68.3k points)

By declaring global variables as global in each function that assigns to it you can use it to see the example below:-

globvar = 0 

def set_globvar_to_one(): 

global globvar 

globvar = 1 

def print_globvar(): 

print(globvar) 

set_globvar_to_one() 

print_globvar()

The reason you should do this is, 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.

0 votes
ago by (20.3k points)

If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.

Say you've got a module like this:

# sample.py

myGlobal = 5

def func1():

    myGlobal = 42

def func2():

    print myGlobal

func1()

func2()

But it'll prints 5 instead of 42. 

As it's already mentioned that, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():

    global myGlobal

    myGlobal = 42

In the above code, Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).

...