Variables are storehouses for values that we wish to use to achieve with programming. Defining variables also helps us to define the nature of operations for which we can use them.
Global & Local Variables
variable_1 = 5 # global variable def function_test(): variable_2 = 10 # local variable print("variable_1 inside is", variable_1) print("variable_2 inside is", variable_2) function_test() print("variable_1 outside is", variable_1)
When we run the above, we get:
Here “variable_1” is a global variable, i.e., it can be accessed anywhere inside the file or if it is imported as a module, and “variable_2” is a local variable and it can only be used inside the function and attempting to do use it outside of a function will produce an error saying the variable is not defined.
Consider modifying the above as shown below:
variable_1 = 5 # global variable def function_test(): variable_1 += 10 print("variable_1 inside is", variable_1) function_test() print("variable_1 outside is", variable_1)
If we try to modify the global variable inside a function, it will produce an error that says the variable was referenced before it was assigned. To modify a variable within a function we need to use the keyword “global”.
variable_1 = 5 # global variable def function_test(): global variable_1 variable_1 += 10 print("variable_1 inside is", variable_1) function_test() print("variable_1 outside is", variable_1)
However, we need to be clear and concise about using global variables, as it can mess with your code. Consider a messy example:
text_1 = "VerificationMaster uses Python" def text_function_1(): global text_1 text_1 = "VerificationMaster uses Python quite extensively" def text_function_2(): global text_1 text_1 = "VerificationMaster uses Python very rarely" print("text_1 is:", text_1) text_function_2() print("text_1 is:", text_1) text_function_1() print("text_1 is:", text_1)
If we change the order of how we call a function, we will get another output.
print("text_1 is:", text_1)text_function_1() print("text_1 is:", text_1)text_function_2() print("text_1 is:", text_1)
Therefore, we must be careful when using the global keyword as it can potentially modify your program in an undesirable way.
Nonlocal Variables
We can make a variable ‘Nonlocal’ using the nonlocal keyword, and a nonlocal variable is used within a nested function. The variable will only belong within the nested functions. A nested function is a function that has one function defined within another function. Consider the following examples:
def function_test1(): var_1 = 5 def function_test2(): nonlocal var_1 var_1 = 10 print("Variable 1 is now:", var_1) function_test2() print("Variable 2 is now:", var_1) function_test1()
We get the output as:
What have we learned?
- What is a local variable?
- What is a global variable?
- How do we modify a global variable?
- What is a nonlocal variable?
- When do we use a nonlocal variable?