Understanding Global, Local and Nonlocal Variables in Python

Understanding Global, Local and Nonlocal Variables in Python
Understanding Global, Local and Nonlocal Variables in Python

Introduction

In the world of programming if you want to perform any operation then variables are the first ones to come into the picture. Variables are something that occupies memory and are used to store different data values for further use in a program.

Now the point is there can be several types of variables such as Global, Local and Nonlocal variables in Python.

Golbal_gif
Source gifhy

And if you are confused about differences among these global, local and non-local variables in Python, then don’t worry, this article is for you. 

We’ll go over each of the “Global, Local and Nonlocal Variables in Python” in-depth here.

Global variables

What do we mean by Global?

It simply means that something that is not restricted to some particular scope.

  • And so are global variables that are not restricted to a particular function of the program.
  • These are variables that can be actually used inside or outside any function of the program.
  • Hence, the scope of a global variable is global, and they are not declared within any particular function.
  • Global variables are generally created at the beginning of a program i.e at the top of a program.

Now, we will see how to create and access a global variable in Python.

Creating and Accessing Global Variable

The declaration of a global variable will be outside all the blocks of the program.

For example:

x = "CodingNinjas"

def main():
    print("x inside:", x)

#calling main function
main()
print("x outside:", x)

Output for Global variables:

x inside: CodingNinjas
x outside: CodingNinjas

x is the global variable in the above Python code.

blog banner 1

What gives us such confidence?

  • To output the value of x within the main, we created a main() function.
  • After that, the print statement outside the main will output the value of x.
  • And they both produce exactly the same results.

Thus, x is a global variable because its value is independent of any function and can be used anywhere in the code.

So now we know how to create global variables in Python but What if we want to modify the value of a global variable in Python?

Modify Global variable in Python

a = 15
print("value before modification",a)
#modify a global value
def modify():
    #let's change the global variable a
    a = a*2
    print("after modification, value in function",a)
 
modify()
print("after modification, value outside the function",a)

Output for Modify Global variable:

value before modification 15

Traceback (most recent call last):

  File "main.py", line 9, in <module>

    modify()

  File "main.py", line 6, in modify

    a = a*2

UnboundLocalError: local variable 'a' referenced before assignment

Here, the value before modification will be printed as 15 but since we tried to modify the value of a global variable inside the function it will give an error because the same-named variable ‘a’ acts like a local variable to that function and so we can’t do the modification this way.

So, now for modification, we will here use the global keyword in python as-.

a = 15
print("value of 'a' before modifying=",a)
#modify a global value
def modify():
    #make the use of a global keyword to change the value actually
    global a
    a=5
    print("after modification,value of'a'in function=",a)
 
modify()
print("after modification,value of 'a'outside the function=",a)

Output for global keyword:

value of 'a' before modifying= 15
after modification,value of'a'in function= 5
after modification,value of 'a'outside the function= 5

From the output, it is clear that now the value is modified, and so, for modifying the value of a global variable outside the context of a particular function, we use the global keyword in python.

Local variables

Above while modifying the global variable without using the global keyword, you must have encountered the word “local variable”. What does it mean by local?

Something whose scope is restricted to a particular scope is local and so are local variables.

  • Local variables have a local scope that is restricted to a particular block in which they are declared.
  • They are basically declared within the definition of a particular function.
  • They cannot be accessed outside the block in which they are declared.

Creating and Accessing local variable

Whatever variables we use in a function are local to that function. So, we declare the local variable in the block where we want to use it, i.e., within the boundary of that function, and thus, its scope gets finished within that block only.

def fun1():
    x=18
    print("Value of 'x' is local to fun1() and x=",x)
def fun2():
    y=20
    print("Value of 'y' is local to fun2() and y=",y)
fun1()
fun2()

Output for local variable:

Value of 'x' is local to fun1() and x=18
Value of 'y' is local to fun2() and y=20

Try to access ‘X in fun1() and ‘y’ in fun2()- 

def fun1():
    x=18;
    print("Value of 'y' is",y)
def fun2():
    y=20;
    print("Value of 'x' is",x)
fun1()
fun2()

So, what do you think is going to happen?

Here you will get an error as-.

Output:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    fun1()
  File "main.py", line 3, in fun1
    print("Value of 'y' is",y)
NameError: name 'y' is not defined

Note: From the above error, it’s clear that a local variable can be accessed within its scope only.

Modifying local variables in Python

Modifying local variables in Python is an easy peasy task as shown below:

def fun1():
    #scope of x is local to fun1
    x=18
    print("Value of 'x' before modification is=",x)
    #try to modify x
    x=x+20
    print("Value of 'x' after modification is=",x)
fun1()

Output for Modifying local variables:

Value of 'x' before modification is= 18
Value of 'x' after modification is= 38

The concept of global and local variables should now be clear to you.

So, just wonder what would happen if there is a local as well as a global variable of the same name in the same program?

#declaring a global variable
p =8;
def fun():
    #local variable with the same name as global variable
    p=18;
    print("value of p=",p)
fun()

Output:

value of p= 18

Hence, when a local variable and global variable have the same name, the priority is given to a local variable of that function, which only gets printed.

Non-local variable

  • The concept of non-local variables is only used by python.
  • It is used where there are nested functions and if we want the variable of the inside function to be non-local.

What exactly does it mean when I say “nested functions”?

A nested function, in general, is a collection of functions declared within another function.

# Python program to illustrate
# nested functions
def outerFunction(num):
number=num

def innerFunction():
    print(number)

innerFunction()

outerFunction(10)

Output for Modifying local variables:

10
  • innerFunction() is an inner function in the example above because it is declared inside outerFunction(). 
  • innerFunction() can only be called after outerFunction() has been called (). After that, outerFunction() will call innerFunction(), which is defined inside it.
  • It is important to call the outer function in order for the inner function to run.

Now let’s try to change the number variable to number=number+10

The reason behind changing it, the moment you write number=number+10

and run the code, you will receive an UnboundLocalError as shown below.

# Python program to illustrate
#scope of local variables
def outerFunction(num):
number=num

def innerFunction():
    #update number inside innerFunction
    number=number+10
   
    print(number)

innerFunction()

outerFunction(10)

Output:

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    outerFunction(10)
  File "main.py", line 12, in outerFunction
    innerFunction()
  File "main.py", line 8, in innerFunction
    number=number+10
UnboundLocalError: local variable 'number' referenced before assignment

Intuitively, If you move it to a global variable by saying the global number, you will get a new problem called NameError.

# Python program to illustrate
#scope of local variables
def outerFunction(num):
number=num

def innerFunction():
    #trying to make it global
    global number
   
    #update number inside innerFunction
    number=number+10
   
    print(number)

innerFunction()

outerFunction(10)

Output:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    outerFunction(10)
  File "main.py", line 15, in outerFunction
    innerFunction()
  File "main.py", line 11, in innerFunction
    number=number+10
NameError: name 'number' is not defined

Definitely, you’ll be confused and unsure of what to do next.

Non-local variables enter the picture now. 

Re-reading the definition, we can infer that if a nested function is present, a nonlocal variable must be used.

Now let’s see the way to create a nonlocal variable and access it.

Creating and Accessing Non-local Variable 

The non-local keyword is used to declare a non-local variable.

def outerFunction():
  #x is a local variable to outerFunction()   
  x =5
  print("value of 'x' in outerFunction=",x)
  def innerFunction():
    #x is nonlocal to innerFunction()
    nonlocal x
    x=6
    print("value of 'x' in innerFunction=",x)
  innerFunction() 

outerFunction()

Output:

value of 'x' in outerFunction= 5
value of 'x' in innerFunction= 6

Let’s see if we can modify the non-local variable or not. We will check it by doing some modifications to the earlier code 

Modifying Non-local variable in Python

def outerFunction():
  #x is a local variable to outerFunction()   
  x =5
  print("value of 'x' in outerFunction=",x)
  def innerFunction():
    #x is nonlocal to innerFunction()
    nonlocal x
    x=6
    print("value of 'x' in innerFunction=",x)
    #let's modify x
    x=x+10
  innerFunction()
  return x

print("x changed to",outerFunction())

Output:

value of 'x' in outerFunction= 5
value of 'x' in innerFunction= 6
x changed to 16

What happened here? Just think of it.

We make changes to the non-local variable that was within the inner function, but the result we obtain was basically from the outer function and the value of ‘x’ is even modified here as it should be x=5 through outside function but since the variable was non-local it’s changing is made for the ‘x’ of outside function as well.

Now that we’ve covered “Global, Local and Nonlocal Variables in Python”, let’s move on to some frequently asked questions about them.

If you have any further questions, please leave them in the comments below; we’d be happy to answer them.

Frequently Asked Questions

What are local and global variables in python?

Local variables are those variables that are declared and used within a particular block or function whereas, global variables are the variables with global scope and can be used either inside or outside any function.

What is a non-local variable in python?

A non-local variable is a variable used when there are nested functions, and we don’t want the variable of the inside function to be local within that function.

Can we modify a global variable in python?

Yes, we can modify a global variable in python using the ‘global’ keyword in the context of the function in which we want the modification to be done.

How can I declare a non-local variable?

A non-local variable can be declared using the ‘nonlocal’ keyword in python.

Is it ok to use global variables in python?

Not exactly, as python considers a variable to be local if not declared as global, and this creates trouble specifically when you want to modify a global variable in python.

Key Takeaways

In this article, we have tried to clarify the difference between “Global, Local and Nonlocal Variables in Python”.

In general, we are well aware of local variables, but it is necessary to know the actual concepts of all three of the variables.

 After covering “Global, Local and Nonlocal Variables in Python”, don’t leave it here only and go through our Guided Path to cover all the Basics in Python and increase your problem-solving skills to fuel up your ride towards cracking your dream job.

Keep learning, keep growing!