When do I need to use the global keyword in python

前端 未结 4 417
攒了一身酷
攒了一身酷 2021-01-03 03:30

Okay, so I\'ve had this really annoying problem where a variable got set locally but then outside of that function reverted to it\'s old self (in this case None), but at the

4条回答
  •  孤独总比滥情好
    2021-01-03 03:50

    If you only need to read the value of a global variable in a function, you don't need the global keyword:

    x = 3
    def f():
        print x
    

    If you ever set the value of a global variable, you need the keyword so that you don't create a local variable:

    x = 3
    def f():
        global x
        x = 5
    
    f()
    print x
    

提交回复
热议问题