品易云推流 关闭
文章详情页
文章 > Python基础教程 > python变量声明为全局变量的两种方法

python变量声明为全局变量的两种方法

python变量

头像

小妮浅浅

2021-09-06 09:59:2017376浏览 · 0收藏 · 0评论

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电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图