Python Global, Local and Nonlocal variables (With Examples)

Global Variables

The variables that are declared outside the scope of a function are defined as global variables in python. Alternatively, the python global variables are considered declared in a global scope. As a result, a user can access a global variable inside or outside the function.

The following example illustrates how a global variable can be created in python:

Creating a Global Variable

                    
x = "global"

def foo():

print("x inside:", x)

foo()

print("x outside:", x)



The output of this snippet will be:

                    
x inside: global

x outside: global



In this particular example, x was created as a global variable. Subsequently, a function foo() was defined to print x.  Lastly, we could print the value of the global variable x by calling f00().

In the same example, however, if one wished to change the value of the global variable inside the function, they would face certain complications:

                    
x = "global"

def foo():

x = x * 2

print(x)

foo()



Now, the output will look something like this:

                    
UnboundLocalError: local variable 'x' referenced before assignment



We get this error because, within the function f00 (), x hasn’t been explicitly declared as a global variable. As a result, Python treats it as a local variable and restricts all attempts to update its value. To avoid situations like these, one needs to use the global keyword.

Let’s take a look at another simple example to gain further clarity:

                    
x = "Python"

print(x)

print(s)

s = "Toppr"

print(s)

func()

print(x)



Here, s is defined as a global variable whereas x is defined as a local variable. Consequently, we can only access within the function in which it is defined, that is func() in this case. If we try to call x outside the scope of func(), then we will encounter the UnboundLocal Error. On the contrary, the global variable s can be called anywhere in the program, including within func(). In other words, the scope of s is the entire program.

Local Variables

Local variables in python are those variables that are declared inside the function. Alternatively, they are said to defined within a local scope. A user can only access a local variable inside the function but never outside it.

Let us take the help of a simple example to understand this.

                    
def sum(x,y):

sum = x + y

return sum

print(sum(5, 10))



The output of this code block will be:

                    
15



In this case, the local variables declared are x and y. They can only be reached within the scope of the function in which they are declared i.e. sum(). Outside the scope of sum(), they don’t exist, and should one attempt to use them, they’ll encounter NameError.
To gain a better understanding of this error, let us consider the following example:

                    
def foo():

y = "local"

foo()

print(y)



The output of this snippet will be:

                    
NameError: name 'y' is not defined



Here, y has been declared as a global variable. Since we tried to access it outside the scope of the function in which it is defined i.e. foo(), we encountered NameError. Thus it is futile to attempt to access a local variable in a global scope because their functionality will always remain confined to a local scope.

Now that we have discussed the scope of existence of a local variable, let us understand how we can create one. The following example illustrates the same:

                    



The output of this code will be:

                    
local



Creating a local variable is a rather simple affair. All one needs to do is declare a variable inside the function.

Global and Local Variables

Now that we have discussed both global and local variables in their individual capacities, let us try and understand how we can use local and global variables in the same code. This will help us modify the values of a variable that doesn’t explicitly get declared as global within a particular function of the code. The following example throws more light on the same:

                    
x = “global “

def foo():
global x
y = “local”
x = x * 2
print(x)
print(y)

foo()



For this particular segment, we will get the output as:

                    
local



In this case, we have declared x as a global variable and y as a local variable within the function foo(). Subsequently, we have tried making use of the multiplication operator (*) to modify the value of the global variable. Lastly, we have printed both x and y. Upon calling the function f00(), we notice that the value of x gets printed twice as “global global”. This is because of the multiplication operation that we performed with the global variable inside foo(). On the other hand, the value of the local variable, y, gets printed only once as local because no operations were carried out on it.

Now let us see see how a program will respond should we happen to assign the same name to a global variable and local variable within it.

                    
x = 5

def foo():

x = 10

print("local x:", x)

foo()

print("global x:", x)



We get the output of this code block as:

                    
local x: 10

global x: 5



Here we assigned the same name “x” to both the global variable and the local variable. However, when we went ahead with printing it, we obtained two different values. This is due to the fact that even though the names of the global variable and local variable is the same, they have been declared in two different scopes. When declared inside the function foo(), the scope is local whereas when it was declared outside that function, the scope became global.

As a result, when we printed the variable that was inside foo(), we got the output as “local x: 10”. This is known as the local scope of the variable. On the other hand, when the variable was printed outside foo(), we got the value as  “global x: 5”. This is known as the global scope of the variable.

Nonlocal Variables

In python, nonlocal variables refer to all those variables that are declared within nested functions. The local scope of a nonlocal variable is not defined. This essentially means that the variable exists neither in the local scope nor in the global scope.

In order to create a nonlocal variable in pyhton, one needs to use the nonlocal keyword. Take a look at the following example to understand how:

                    
def outer():
x = “local”

def inner():
nonlocal x
x = “nonlocal”
print(“inner:”, x)

inner()
print(“outer:”, x)

outer()



We obtain the output of this code as:

                    
inner: nonlocal

outer: nonlocal



Here, the inner() function is nested in nature. The nonlocal keyword has been used to create a nonlocal variable. As we can see, the inner() function in itself is defined within the scope of another function i.e., outer().  An important point to be noted here is that if one were to modify the value of a nonlocal variable, the changes carried out would manifest themselves in the local variable as well.

Q1. How do you declared a global variable in python?

Answer: The python global variable is declared with the help of the global keyword. The scope of a global variable is the entire program.

Q2. What is a global variable in python?

Answer: The variables that are declared outside the scope of a function are defined as global variables in python. As a result, a user can access a global variable inside or outside the function.

Q3. Is it OK to use global variables in python?

Answer: In python, the usage of global variables is considered bad practice and should generally be avoided. Instead the user can try and use a parameter for passing a value onto a function or return a value to obtain it.

Q4. How do you declare a global list in python?

Answer: A global list can be declared in python by first specifying a function to do and then explicitly specifying the variables to be global within that function.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
Ashhar Firdausi
IIT Roorkee
Biology
Dr. Nazma Shaik
VTU
Chemistry
Gaurav Tiwari
APJAKTU
Physics
Get Started