USING GLOBAL VARIABLES IN A FUNCTION OTHER THAN THE ONE THAT CREATED THEM

Samuel Fernandes

Total Post:159

Points:1117
Posted by  Samuel Fernandes
Python 
 573  View(s)
Ratings:
Rate this:
If I create a global variable in one function, how can I use that variable in another function?
Do I need to store the global variable in a local variable of the function which needs its access?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Using global variables in a function other than the one that created them

    You can use a global variable in other functions by declaring it as global in each function that assigns to it:

    globvar = 0
    def set_globvar_to_one():
        global globvar    # Needed to modify global copy of globvar
        globvar = 1
    def print_globvar():
        print globvar     # No need for global declaration to read value of globvar
    set_globvar_to_one()
    print_globvar()       # Prints 1
    I imagine the reason for it is that, 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.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!