-1
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" ?

D.joe
  • 31
  • 3
  • 1
    Possible duplicate of [Use of "global" keyword in Python](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) – khelwood Sep 26 '17 at 09:47
  • 1
    These do completely different things. Did you try? What was the output? – Daniel Roseman Sep 26 '17 at 09:48
  • when you type global keyword it gain access to variable outside to function func() scope and can change its value but when you just type variable =None or variable = 1 you are creating a new local variable – Vaibhav Sep 26 '17 at 09:49

3 Answers3

2

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.

LITDataScience
  • 380
  • 5
  • 14
1

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.

  • Just like apples and oranges: ```variable = None``` is not leading in any result close to ```global variable```, so the comparison is a bit awkward. – Evgeny Sep 26 '17 at 09:55
1

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.

Jayson Chacko
  • 2,388
  • 1
  • 11
  • 16