Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k 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 (106k 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(): 




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
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:


myGlobal = 5

def func1():

    myGlobal = 42

def func2():

    print myGlobal



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).

Related questions

0 votes
1 answer
asked Aug 5, 2019 in Python by Sammy (47.6k points)
+1 vote
2 answers
+1 vote
2 answers
asked May 29, 2019 in R Programming by Suresh (3.4k points)
0 votes
1 answer

Browse Categories