What are global variables and how to use Global Variables inside a function in Python? Don’t worry we will answer this question very shortly. Also, we will take you through a couple of examples followed by practice questions to make you just about ready for the topic! Before we jump into the primary subject of discussion, let us understand in brief the memory allocations in Python.
Understanding memory allocation in Python
Firstly, variables in Python are reserved memory locations where a user can store their data values. When we declare a variable, the interpreter ensures to reserve some part of the memory in the name of that variable. And the variable then utilizes that memory location for storing the data. That is to say, the names that were given to the variable act as a referencing tag. And these referencing tags mention the reserved blocks of memory.
Thus, after we declare and initialize the variables inside a program, we can access them within the program. However, we need to realize that not all variables can be accessed anywhere inside the program. On the other hand, the part of the program where a variable can be accessed inside the program is called the scope of the variable. To clarify, there are multiple types of variable scope like a local variable, global variable, non-local variable. This article will discuss global variables and their usage inside a Python program in detail.
What are global variables?
The variables that we declare outside a function are called global variables. We can reference such variables from anywhere inside the program. Hence, the scope of the variable is global. They can be accessed from inside or outside of the function. Let’s learn more about these by implementing a practical example:
In the above-written program, we firstly declared a variable named var that stores a string inside it. It should be noted that this variable is declared outside a function. Now, we declare a user-defined function having name custom_function(). Then, inside the function, we print the data stored inside the var variable. Also, an external print statement is written outside of the function block that prints the data that we store in the var variable. When we execute and run this program, we will get the output as given below:
If we observe the program’s output, we can see the value stored inside the var variable is the same when we try to access from inside the function or from outside the function. Thus, it can be verified that globally declared variables can be accessed from anywhere inside the program.
Manipulating the value stored in a global variable inside a function
To this point, accessing the values in a global variable inside a user-defined function was handy. We were able to do it easily as global variables are accessible from anywhere inside the program. Now, let’s try to manipulate the value of a global variable inside the function. Let us find out whether the changes occurring inside the function get reflected globally or not.
Upon executing the above-written program, we obtain the following output
From the output, we can see the interpreter throws a traceback (error). It says that the local variable ‘var’ needs a definition when we try to update the value stored inside the global variable. This happens because the Python interpreter assumes any variable to be a local variable inside the function when we try to perform the update operation over that variable. That is why here the program throws an error saying local variable ‘var’ needs a definition. Hence, we can conclude that we cannot assign other values to the global variables. Also, we cannot update the global variables inside a function. To overcome this situation, we make use of the global keyword.
Using global Variables inside a function
The global keyword is used to make a local variable turn into global and allows making changes to the variable in the local context. Let’s turn ourselves back to the previous example but this time after making some subtle changes.
To be able to assign and manipulate the global variable ‘var’ inside the function, we declare it with a global keyword inside the function. Now, as we try to make changes in the ‘var’ variable, the interpreter does not interpret it as a local variable and hence, changes can be made easily.
Upon compiling and executing the above code, the output we will see will be given as:
The changes that we make to the global variable inside the function will be visible throughout the program, as seen from the last print statement written outside the function body.
Local and global variables having the same name inside a function
Let’s see the behavior of the function when we use both local and global variables having the same name inside the program.
We first have declared the ‘var’ variable globally and later inside the function declare again a local variable with the same name ‘var’. When we call the function the print statement executed inside the function prints a value. We can see that the value which the print statement prints are the local variable inside the function. On the contrary, when the control of the program goes outside of the block and the second print statement executes, the value that it prints is of the global variable. This is because the scope of the local variable remains inside the function block only. The output is as shown below:
Test your understanding of the scope of variables in Python. Attempt these practice MCQs.
See if you are clear with the concept on the use of global variables inside a function in Python:
Question 1. What will be the output of following code? var_1 = 9 if True: var_1 = 16 var_1 = var_1 + 34 # outside the if block print(var_1) i. 16 ii. 9 iii. 34 iv. 50 Correct Answer: (iv.) 50
Question 2. What will be the output of following code? var_1 = 50 def func(var_2): var_1 = 77 var_1 = var_2 return (var_1)%10 # ouside the function block print (func(1)) i. 1 ii. 50 iii. 77 iv. 7 Correct Answer: (i) 1
Question 3. Scope resolution in Python is based on which of the following rule? i. DMAS rule ii. LEGB rule iii. LBEG rule iv. BGEL rule Correct Answer: (ii) LEGB rule The interpreter uses the LEGB rule in Python to decide the order in which it looks out for namespace in the program. It also uses the same and performs scope resolution. The hierarchy that is to be followed for scope resolution is given as Local -> Enclosed -> Global -> Built-in.
Question 4. Which of the following keyword can transform the scope of the variable from local to global? i. global ii. convert_global iii. __global__ iv. None of these Correct Answer: (i) global We make use of the global keyword to make a local variable turn into the global scope.
Question 5. Which of the following is not a reserved keyword in Python? i. for ii. global iii. type iv. none of these Correct Answer: (iv) none of these All the keywords given above are reserved keywords. The reserved keywords are so-called because we cannot use them as ordinary identifiers. We use the ‘for’ keyword to denote a ‘for’ loop. The ‘global’ keyword is used to define a global variable. The ‘type’ keyword determines the type of Python object, we use.
We hope this article could throw some light on using global variables inside a function in Python. For more such articles and tips and tricks in Python, keep up-to-date with our blogs.
If you wish to master Python skills, then GUVI is the best EduTech platform you can look forth to! Keep Learning. keep Growing!