Home >Backend Development >Python Tutorial >How to define global variables in python
In python, global variables can be defined anywhere outside the function. When using global variables inside a function, you need to use the global
keyword to declare the variable as a global variable. Here is an example:
# 定义全局变量 global_var = 10 def my_function(): # 使用全局变量 print(global_var) def another_function(): # 修改全局变量 global global_var global_var = 20 # 调用函数 my_function() # 输出:10 another_function() my_function() # 输出:20
In the above example, global_var
is a global variable, which is used and modified in the my_function()
function. In the another_function()
function, the global
keyword is used to declare global_var
as a global variable, and then its value is modified. Finally, call the my_function()
function again, and you can see that the value of the global variable has been modified to 20.
The above is the detailed content of How to define global variables in python. For more information, please follow other related articles on the PHP Chinese website!