SyntaxError when assigning to global var

前端 未结 5 1116
星月不相逢
星月不相逢 2021-01-26 11:36

I am trying out Python for a new project, and in that state, need some global variable. To test without changing the hardcoded value, I\'ve tried to make a function that reassig

5条回答
  •  佛祖请我去吃肉
    2021-01-26 11:59

    Python doesn't require you to explicitly declare variables and automatically assumes that a variable that you assign has function scope unless you tell it otherwise. The global keyword is the means that is provided to tell it otherwise. And you can't assign value when you declare it as global. Correct way will be

    foo = None
    
    def setFoo(bar):
        global foo 
        foo = bar
    
    setFoo(1)
    

提交回复
热议问题