Local and Global Variable in Python Programming
Local and Global variables: We have already discussed variables in our previous topics. Local and Global variables play a vital role while working with functions.
Many times, if you are not aware of local and global variables term, then there will be a chance that once you will surely be stuck into the problem while solving complex programs. Let’s discuss each of this term one by one.
Global Variable in Python: Like it, names defines “Global” which means it can be accessible everywhere. Now listen carefully when we define a function, then we can also create a variable inside our function.
It is also possible that one variable is already there outside of a function. Now we have two variables: One is inside the function and the second one is outside of the function. Let’s see the below-given diagram to make it more clear:
The variable defined outside of a function is called “Global” and the variable defined inside a function is called “Local” variable.
Important: Scope of the Global variable is everywhere inside the program. We can access the global variable even inside the function also. But the scope of the local variable is limited. It is only accessible inside the function only where it has been defined or declared.
We cannot use a local variable outside of the function. If we do so, then the compiler will generate an error as a variable is not defined.
Example 1: What if we try to access a local variable outside of function? Let’s see with the help of an example:
#Local and Global variable x = 23 #This is the Global Variable def fnc_name(): y = 24 #This is Local Variable print(y) fnc_name() print(y)
Output:
#Output #Error: variable not defined
Question: If we define a local variable and a global variable with the same name.When we print the variable inside a function, which variable will be printed “Local” or “Global”.
Answer: Local variable has the highest preference inside the function. It will first check for the local variable inside function. If local variable is present inside function, then it will go with the local variable else it will go with a global variable.
Example 2:
#Local and Global variable x = 23 #This is the Global Variable def fnc_name(): x = 24 #This is Local Variable print(y) fnc_name()
Output:
#Output #24
Example 3:
#Local and Global variable x = 23 #This is the Global Variable def fnc_name(): x = 24 #This is Local Variable print(x) fnc_name() print(x)
Output:
#Output #24