• 技术文章 >Python技术 >Python基础教程

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

    小妮浅浅小妮浅浅2021-09-06 09:59:20原创17613

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

    1

    2

    3

    4

    5

    6

    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。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

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

    专题推荐:python变量
    上一篇:python列表如何分成大小均匀的块 下一篇:Python解释器如何读取源文件

    相关文章推荐

    • python变量可以用汉字吗?• python变量如何加入到文件路径• python变量命名为什么数字不能开头?• 如何使用python变量?• python变量作用域是什么?• python变量有几种作用域类型• python变量如何拼接• python变量的概念及定义• python变量的赋值和优势• python变量如何在作用域使用• python变量中self的添加• python变量如何进行格式化输出

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网