Variables are the reserved memory location for storing value.
Here, in this article we will discuss about the python global variable, python local variable and python non-local variable with examples.
Global Variable
In python, global variables are those variables which are declared outside of the function or are declared in the global scope. Global variable can be used everywhere in a program by the programmers and the scope of these variables are available through the entire program and inside every function.
Python Global Variable Example;
x = "Python Global variables"def pre():
print("Welcome to:", x)
pre()
print("let's learn:", x)
Output
Welcome to: Python Global variables
let's learn: Python Global variables
x = "Python global variables"def pre():
x = x * 4
print(x)
pre()
Output
UnboundLocalError: local variable 'x' referenced before assignment
Here, we get error as a result because is treated as local variable in python and inside the , not defined. To make the above condition work, we have to use the python global keyword.
Local Variable
In python, local variables are those variables which are declared inside of the function or are declared in the local scope. Local variables only belongs to that particular function in which it was declared. And we can not access local variables from outside of the function.
Python Local Variable Example;
def pre():x = "Python Local Variables"
print(x)
pre()
Output
Python Local Variables
def pre():x = "Python Local Variables"
print("Inside Function:", x)
pre()
print(x)
Output
NameError: name 'x' is not defined
Non-local Variable
In Python, Non-local variables are those variables which are declared inside the nested function and they don't have any defined local scope. Simply we can say that Non-local variables are neither declared in local scope nor the global scope.
Python Non-local Variable Example;
def func():x = "Answersjet"
def fn():
nonlocal x
x = "Python Non-local Variables"
print("Welcome to:", x)
fn()
print("let's learn:", x)
func()
Output
Welcome to: Python Non-local Variables
let's learn: Python Non-local Variables
Conclusion
From the above information we have learnt about the Global, Local and Non-local variables. Python Global variables are those variables which are declared outside of the function. Python Local variables are those variables which are declared inside of the function. Python Non-local variables are those variables which are declared inside the nested function.