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
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)
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 :)
foo = None;
def setFoo(bar):
global foo
foo = bar
setFoo(1);
global and assignment are both statements. You can't mix them on the same line.
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?