SyntaxError when assigning to global var

前端 未结 5 1114
星月不相逢
星月不相逢 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 12:00

    As saurabh baid pointed out, the correct syntax is

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

    Using the global keyword allows the function to access the global scope (i.e. the scope of the module)

    Also notice how I renamed the variables to be snake_case and removed the semi-colons. semi-colons are unnecessary in Python, and functions are typically snake_case :)

提交回复
热议问题