Use of “global” keyword in Python

后端 未结 10 2423
既然无缘
既然无缘 2020-11-21 05:05

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to us

10条回答
  •  隐瞒了意图╮
    2020-11-21 05:30

    While you can access global variables without the global keyword, if you want to modify them you have to use the global keyword. For example:

    foo = 1
    def test():
        foo = 2 # new local foo
    
    def blub():
        global foo
        foo = 3 # changes the value of the global foo
    

    In your case, you're just accessing the list sub.

提交回复
热议问题