后浪云Python教程:python变量声明为全局变量的两种方法

后浪云Python教程:python变量声明为全局变量的两种方法插图

1、在函数内部分配变量并使用global line。

def declare_a_global_variable():
    global global_variable_1
    global_variable_1 = 1
 
# Note to use the function to global variables
declare_a_global_variable()

2、在函数外赋值。如果想在另一个函数中更改global line,update_variables()应该在分配变量之前使用global。

global_variable_1 = 1
global_variable_2 = 2
 
def update_variables():
    global global_variable_1
    global_variable_1 = 11
    global_variable_2 = 12 # will update just locally for this function
 
update_variables()
print(global_variable_1) # prints 11
print(global_variable_2) # prints 2

以上就是python变量声明为全局变量的两种方法,希望对大家有所帮助。更多Python学习指路:后浪云python教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END