How to define global variables and local variables in Python?
In Python, global variables and local variables are defined as follows:
- Global variables are variables that can be accessed and modified within the entire program, they can be defined outside of any function in the program.
global_variable = 10 # 全局变量
def function():
# 访问全局变量
print(global_variable)
# 修改全局变量
global global_variable
global_variable = 20
function() # 输出:10
print(global_variable) # 输出:20
- Local variables: These are variables defined within a function and can only be accessed and modified within that function. Their scope is limited to the function in which they are defined.
def function():
local_variable = 10 # 局部变量
print(local_variable)
function() # 输出:10
print(local_variable) # 报错,局部变量不可在函数外部访问
It is important to note that if you need to modify a global variable within a function, you must use the “global” keyword to declare the variable as global within the function. Otherwise, Python will consider it as a local variable.