Site icon Virtual Maestro

Learning Python Part-22: Variable Scopes

Variable scope is the portion of the program from where a variable can be accessed directly without any prefix. 
Although there are unique variables defined, we may not be able to access all of them from every part of the program as they may be defined at various places like in main program, inside function, inside nested function. This is where concept of scope comes into play.
There are three scopes that are generally used in Python programs.
  • Local
  • Global
  • Built-in

When a reference variable is made inside a function, the name is searched in the local namespace first, then in the global namespace and finally in the built-in namespace.

If there is a function inside another function (nested function), a new scope is nested inside the local scope.

Python Global, Local and Nonlocal variables:

Global Variables

  • In Python, a variable declared outside of the function or in global scope is known as global variable.
  • This means, global variable can be accessed inside or outside of the function.

x = “global”
def func():
      print(“x inside :”, x)

print(“x outside:”, x)

Global Variables Across Python Modules:

  • In Python, we create a single module to hold global variables and share information across Python modules within the same program.
  • Here is how we can share global variable across the python modules.


  • Create a file, to store global variables

a = 0
b = “empty”

  • Create a file, to change global variables

import config
config.a = 10
config.b = “Python”

  • Create a file, to test changes in value

import config
import update

  • When we run the file, the output will be


Global in Nested Functions:

def func():
      x = 20
      def bar():
            global x
            x = 25
       print(“Before calling bar: “, x)
       print(“Calling bar now”)
       print(“After calling bar: “, x)

print(“x in main : “, x)

Local Variables : 
A variable declared inside the function’s body or in the local scope is known as local variable.


def myfunc():
      y = “local”


Non-local Variables:

Nonlocal variable in a nested function:
  • A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope.
  • In Python, these non-local variables are read only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
  • Following is an example of a nested function accessing a non-local variable.
def printmsg(msg):
      def printer():
printmsg(“Hello World”)
  • We can see that the nested function printer() was able to access the non-local variable msg of the enclosing printmsg() function.
Non-local variable are also used in nested function whose local scope is not defined.
  • This means, the variable can be neither in the local nor the global scope.
  • We use nonlocal keyword to create nonlocal variable. 


Exit mobile version