We all know that we can create variables(arguments) inside functions.
So, In case if you don’t know click here
Can we create variables outside the function ?
yes ,we can
let’s see a simple example here,
a=1 def some(): a=15 print("fun" ,a) some() print("outside" ,a)
fun 15 outside 1
here we’ve created 2 values for the variable a one is outside the function with the value of a=1 another with a value of a=15 inside the function
the variable a=1 outside function called a global variable the a=15 inside the function called a local variable
we can access global variables inside a function unless there is no variable with the same name
if we have a variable inside the function it will be taken as the first priority the global variable taken
if we didn’t have the local variable but in the case of the local variable, it can only be used inside its function we can access the variable side the function
How to access the global variable in the presence of the local variable inside the function? and example
we can access the global in spite of local by mentioning the Global keyword
a=1 def some(): global a a=15 print("fun" ,a) some() print("outside" ,a)
fun 15 outside 15
in this code, we can see the keyword global inside the function therefore python will take the value of a from the global variable instead of the local variable inside the function
Can we change the value of Global variable inside the function?
yes we can do it with a special function called globals ()
a=1 def some(): a=15 x=globals()['a'] print("fun" ,a) globals()['a']=99 some() print("outside" ,a)
fun 15 outside 99
Here a=1 is outside the function so it is a global variable and at the same time one more variable is created inside the function which is known as the local variable but in this case
we need to access the global variable however the local variable is present after that we’ve to change the value of the global variable.
for that instance, we’ve created a dummy variable named x which is used to access the particular global variable a
we can use the same syntax inside the function to assign a new value for the global value a
and we can check by printing the variable and we can see that the global variable is updated
Unused variables are used in the integrated functions that do not reflect its size
def outside(): x = "local" def inside(): nonlocal x x = "nonlocal" print(inside:", x) inside() print("outside:", x) outside()
inside: non local Outside: non local
In this example code, we can see there is a nested inside() function. We use nonlocal keywords to create a nonlocal variable.
inside() the function defined the scope of another function outside().
And the important key point to be remembered is changing the value of the non local variable, the changes will be appear in the local variable.