Home >Backend Development >Python Tutorial >How Do I Use Global Variables Effectively Within and Across Python Functions?
In Python, variables defined within a function are local to that function. However, sometimes it is necessary to access or modify a variable across multiple functions. This is where global variables come into play.
To create a global variable within a function, you must use the global keyword. This keyword must be used before assigning a value to the variable:
globvar = 0 def set_globvar_to_one(): global globvar # Declares globvar as a global variable globvar = 1
Important Note: The global keyword is only required when modifying the value of the global variable. It is not necessary when accessing its value.
Once a global variable is declared within one function, you can use it in other functions by simply referencing its name:
def print_globvar(): print(globvar) # No global declaration is required to read the variable
Consider the following example:
globvar = 0 def set_globvar_to_one(): global globvar globvar = 1 def print_globvar(): print(globvar) set_globvar_to_one() print_globvar() # Prints 1
In this example, globvar is set to 1 in the set_globvar_to_one function, and the value is then printed in the print_globvar function.
It is important to note that global variables are only shared within the current module. If you want to share a global variable across multiple modules, you can use the __init__.py file in the parent directory to define the variable and import it into the desired modules.
The above is the detailed content of How Do I Use Global Variables Effectively Within and Across Python Functions?. For more information, please follow other related articles on the PHP Chinese website!