Question:

How Will You Set A Global Variable Inside A Function?

Answer:

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.


Keywords:

© 2017 QuizBucket.org