How do I create or use a global variable in a function?
If I create a global variable in one function, how can I use it in another function? Do I need to store global variables in local variables of functions that need access?
Global variables can be used by other functions by declaring them as global in each function they assign.
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
Reference: https://python5.com/q/biukniir
Recommended Posts