SyntaxError when assigning to global var

前端 未结 5 1112
星月不相逢
星月不相逢 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)
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2021-01-26 12:03
    foo = None;
    
    def setFoo(bar):
        global foo 
        foo = bar
    
    setFoo(1);
    
    0 讨论(0)
  • 2021-01-26 12:04

    global and assignment are both statements. You can't mix them on the same line.

    0 讨论(0)
  • 2021-01-26 12:21

    global and foo = bar on separate lines

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

    don't use semicolon: Python: What Does a Semi Colon Do?

    0 讨论(0)
提交回复
热议问题