20.Global,local and non local variables
Global Variables
x = "global"
Using Global and Local variables in the same code
x = "global "
Global variable and Local variable with same name
x = 5
Nonlocal Variables
In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.
Let's see an example of how a global variable is created in Python.
Example 1: Create a Global Variablex = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
Output
Output
x inside: global
x outside: global
Global Variables can be modified in functions with the keyword global
X=10
def inc():
global X
X=X+1
def dec():
global X
X=X-1
print(X) # this will print 10
inc()
print (X) # this will print 11
dec()
dec()
print (X) #this will print 9
def inc():
global X
X=X+1
def dec():
global X
X=X-1
print(X) # this will print 10
inc()
print (X) # this will print 11
dec()
dec()
print (X) #this will print 9
Using Global and Local variables in the same code
x = "global "
def foo():
global x
y = "local"
x = x * 2
print(x)
print(y)
foo()
Output
Output
global global
local
In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use multiplication operator * to modify the global variable x and we print both x and y.
After calling the foo(), the value of x becomes global global because we used the x * 2 to print two times global. After that, we print the value of local variable y i.e local.
Global variable and Local variable with same name
x = 5
def foo():
x = 10
print("local x:", x)
foo()
print("global x:", x)
Output
Output
local x: 10
global x: 5
In the above code, we used the same name x for both global variable and local variable. We get a different result when we print the same variable because the variable is declared in both scopes, i.e. the local scope inside foo() and global scope outside foo().
When we print the variable inside foo() it outputs local x: 10. This is called the local scope of the variable.
Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the global scope of the variable.
Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.
Let's see an example of how a global variable is created in Python.
We use nonlocal keywords to create nonlocal variable
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
Output
inner: nonlocal
outer: nonlocal
In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal variable. The inner() function is defined in the scope of another function outer().
Note : If we change the value of a nonlocal variable, the changes appear in the local variable.
Comments
Post a Comment