variable= 0
def func():
global variable #(or variable = None)
variable = 1
def display():
print(variable)
func()
display()
What is the difference between "global variable" or "variable = None" ?
variable= 0
def func():
global variable #(or variable = None)
variable = 1
def display():
print(variable)
func()
display()
What is the difference between "global variable" or "variable = None" ?
I think the major difference is that declaring global will open it's scope to all the functions. But declaring it as None will just initialize an uninitialized variable and creating a new local variable.
The default scope of a variable inside a function will be local. So, when you assign variable = None, you are creating a local variable and assigning none to it. Whereas, if you declare it as global, you'll be modifying the global variable that you initialized earlier.
In python, any global variables initialized outside a function is accessible inside a function. However this access is automatic only if you are using it as a read only variable.
If you assign to the same name inside a function, a new variable of local scope is created. The global keyword tells python that you don't want a local instance, but would like to modify the global variable outside.
So in your example func() modifies the global variable and the same variable is accessible from display() in read only mode even without the global keyword. However if you assign None to the variable in func() without global keyword, you are creating a new local variable. Hence in display() you will see the unmodified global variable.