Python Scope – global, local and nonlocal Variables

Python Scope

This is a detailed tutorial of the Python Global, Local & Non-Local Variables. Learn variable scopes & where to use which type of variables in your program.

On the basis of their scopes, the python variables are categorized into three types, namely, Global, Local and Non-Local variables. Now, many of you might be thinking, what scope, I’m talking about? The scope of variables is a common concept in most programming languages. Every programming language has the concept of functions. There are variables written inside functions and there are also variables written outside the functions.

Now, you may or may not access the variables that are written inside the function, outside somewhere, or inside some other function by the reference of the variable name. Here comes the concept of scope, i.e. up to which part of the variable is accessible by reference. In other words, every variable has a scope area up to which it can be used.

Let’s understand the different types of variables in python according to their scope.

Global Variables

Global Variables are the variables that can be used anywhere in your entire python program. In other words, these are the variables with global scope. They can be used outside of any function or can also be referred to inside any function. Every variable that is written in a python program, outside of any function is a global variable.

Let’s understand the concept of Global Variables with the help of an example.

Example 1. Creating a Global Variable

#Example 1: Global Variable Creation

#A Global Variable
a = "Hi! I am a Global Variable"

#Accessing Global Variable Inside Function
def insideFunction():
    print(a + " I can be accessed inside the function.")
    
#Calling the function
insideFunction()

#Accessing Global Variable Outside function
print(a + " I can be accessed outside the function.")

In the above python code, I’ve simply created a variable a outside any function. Then I’ve defined a function named insideFunction() with a single print statement in its body that accesses the variable a and concatenates it with another string to print a final string.

Afterward, I simply called this function, so that this function can actually be able to execute the print statement. Then, I’m accessing the variable a outside any function to be used in the print statement along with concatenation to another string object.

Example 2. Global variable works as Local Variable inside a Function

In the above example, we’ve directly used the global variable a to be used inside the print statement of a function. But what if I’ve to modify the value of this variable?

Have a look at the following example.

#Example 2: Global Variable work as Local Variable inside Function

#A Global Variable
a = "Hi! I am a Global Variable"

#Accessing Global Variable Inside Function
def insideFunction():
    #a here acts as a Local Variable
    a = "I am changed inside function."
    print(a + " I can be accessed inside the function.")
    
#Calling the function
insideFunction()

#Accessing Global Variable Outside function
#Value of a does not change here
print(a + " I can be accessed outside the function.")

Here, I’ve taken the same example as above but I’ve made some changes. Inside the function, I’ve modified the value of the variable a. Now, carefully observe the output of this program.

The value of a that was modified is only used for the print statement inside the function, while for the second print statement written outside of any function, prints the same old value of the variable a that was initially defined.

This shows that the variable the global variable a inside of a function acts as the Local variable and any change to its value inside the function will not overwrite the original value of the global variable.

Still, if you want that if the modified value of the variable a inside of the function to reflect outside of the function as well, then you’ve to make use of the global keyword to make the local variable a inside of the function a global variable. This is illustrated later in this article after the Local Variables section.

This concept is also known as the Global & Local Variable of the same name. The variable a inside the function and the global variable a outside the function are here actually two completely different variables. That is why the change in the value of a inside the function has no effect on the value of the global variable a outside of the function.

Local Variables

As you might have already guessed that the Local Variables are the variables defined inside the body of the Python Functions. They are called local because they have local scope. In other words, they can be accessed only inside the particular function in which they are defined and can not be accessed anywhere outside or inside other functions.

Example 3. Defining a Local Variable & Trying to Access Outside the Function

In the following example, we’ve defined a variable a inside the function named insideFunction().

def insideFunction():
    #Local Variable
    a = 5
    print("Local Variable a:", a)
    
#Calling the Function
insideFunction()

#Accessing a Outside Function
#Will raise Error
print("Local Variable a:", a)

As you can see in the output screenshot, the variable print statement of the function is executed properly, and the value of the variable a is accessed within the function. But when the local variable a is tried to be accessed from outside of the function, it raises the NameError.

Using Local Variables as Global Variables

In the first section about Global Variables, you have seen that If we modify the value of the variable inside the function, is modified value has not reflected the value of the same variable outside the function. This is due to the fact that Global variables act as Local variables inside the function. We’ve already discussed this.

Now, let’s find out how you can make use of explicitly making the local variables of the function global so that the modified value of the variable inside the function can also be reflected in the global variable outside of the function as well.

Example 4. Use of global keyword to make a Local Variable a Global Variable

Before showing you the correct use of the global keyword, have a look at the following program that does not make use fo the global keyword, and gives the UnboundLocalError.

#Example 4. Use of global keyword to make Local Variable a Global Variable
#Case 1
a = 10

def insideFunction():
    a = a + 5
    print("Inside Function: " + str(a))
    
insideFunction()

print("Outside Function: " + str(a))

This error is raised because of the statement a = a + 5 inside the function. As I mentioned that the variable a inside the function acts as a Local variable and here we’ve not actually defined the value for the local variable a and how can add the value of the variable a?

To tell the compiler here to get the same value of the global variable a as outside the function here also, you’ve to use the global keyword as illustrated in the following example.

#Example 4. Use of global keyword to make Local Variable a Global Variable
#Case 1
a = 10

def insideFunction():
    global a
    a = a + 5
    print("Inside Function: " + str(a))
    
insideFunction()

print("Outside Function: " + str(a))

Now, as shown in the following output screenshot, the value of the variable a is modified throughout the program.

Unlike Example 2, in which the local variable a and global variable a were two different variables. Here both of the variables are actually the same because by using the keyword global, we’re defining both of them to be the same global variable. Hence, the value of these variables is the same inside as well as outside the scope of the function.

Non-Local Variables

Non-Local Variables are used inside the function. These are used when a variable is neither in the Local Scope nor in the global scope. This is a type of scope that can be used inside all the nested levels of functions. The keyword nonlocal is used to create a Non-Local variable. This concept might be pretty confusing for many of us. Have a look at the following examples to clear up all the confusion.

Two examples are given below. The first example makes do not make use of the nonlocal keyword while the second one makes use of the nonlocal keyword. Observe the difference in the output of both of these and you will be all sorted about the purpose and the use of the nonlocal variables.

Example 5. Nested Functions without the use of nonlocal Variables

In the following code, we have got a nested function with 2 levels. In both these levels, we have defined two different values for the variable a.

#Without the use of nonlocal Keyword
#Level 1
def level1():
    a = 5
    #Level 2
    def level2():
        a = 10
        print("In Level 2:",a)
    #Calling level2()
    level2()
    print("In Level 1:",a)
    
#Calling Level1
level1()

You can see in the output that the value of the variable a is different in both of the levels and hence is printed differently as well. This implies that the variable a in the level is different from the variable a in level 2.

Now, what do we want the variable a to remain the same and work as a global variable between the nested functions? Then comes the use of the nonlocal keyword.

Example 6. Nested Functions with the use of nonlocal Variables

The following example is the same as above, the only difference is that we’ve just used the nonlocal keyword for the variable a in level 1 to make it a nonlocal variable.

#With the use of nonlocal Keyword
#Level 1
def level1():
    nonlocal a
    a = 5
    #Level 2
    def level2():
        a = 10
        print("In Level 2:",a)
    #Calling level2()
    level2()
    print("In Level 1:",a)
    
#Calling Level1
level1()

Now, the value of the variable a remains the same inside the level1 and well as the level2 functions.

Leave a Reply

Your email address will not be published. Required fields are marked *