Global variable
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.
m = 0
def f(x):
print(m)
return x
m
variable scope can be accessed out of the function f(x)
.
Local variable
A local variable is a variable which is either a variable declared within the function or is an argument passed to a function. As you may have encountered in your programming, if we declare variables in a function then we can only use them within that function.
def f(x):
m = 0
print(m)
return x
m
can only be accessed in function f(x)
.
~ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> m = 3
>>>
>>>
>>> def f(x):
... global m
... m = m + 1
... print(m)
...
>>>
>>> def g(x):
... print(m)
...
>>>
Please see the execution flow:
>>> m <---- original value
3
>>> f(3) <---- m = 3; m = m + 1; m = 4
4
>>> m
4
>>> f(3) <---- m = 4; m = m + 1; m = 5
5
>>> m
5
Wish this can help you.