In Python, a variable defined within a function is normally confined to that function. However, it's possible to modify or access a variable in the global scope from within a function using the global keyword.
Creating or Using a Global Variable Within a Function
To declare a variable as global within a function, use the following syntax:
global variable_name
Place this declaration at the beginning of the function where you need to modify or use the global variable. For example:
globvar = 0 def my_function(): global globvar globvar += 1 print(globvar) # Prints the updated value of globvar
Using a Global Variable in Multiple Functions
Once a variable has been declared as global in one function, you can then use or modify it in other functions without redeclaring it. Here's an example:
def function_1(): global globvar globvar += 1 def function_2(): global globvar print(globvar) # Prints the updated value of globvar
In this case, both functions share the same global variable globvar. By modifying globvar in function_1, its value is also changed for function_2.
Note:
The above is the detailed content of How Can I Modify Global Variables from Within Python Functions?. For more information, please follow other related articles on the PHP Chinese website!