Close
Close

Python Scope of Variables


Till now, we have used variables in most of our programs. However, there are cases where a variable declared in one part of a program can’t be accessed in some other part of the program. We will look at those cases in this chapter.

Scope is a region of a program. Scope of a variable is the region in a program where that variable can be accessed. For example, suppose a variable x can be accessed only inside a particular function, then the scope of x is inside that function.

Variables are thus of three types depending on the region where these are created and used.

Python Local Variables


Variables that are declared inside a function can only be used within that function. Such variables which are declared inside a function are called local variables of that function and are said to have local scope. Therefore, local variables can only be used within the function in which they are declared.

Let's take one example to see that local variables belong to the function in which they are declared.

def func1():
    x = 10
    print(x)

def func2():
    x = 20
    print(x)

func1()
func2()
Output
10
20

In the function func1, we declared a variable x and assigned it a value 10. This variable is in the body of the function func1 and thus gets destroyed when the body of the function ends. So, when we call func1, 10 gets printed.

We declared another variable x in the function func2 and gave it a value 20. This variable also gets destroyed as the body of func2 ends and has no relation with the variable x of func1.

So, the two variables are independent of each other and are limited to only the function in which they are declared. The scope of the variable x is within the function func1 and that of y is within the function func2.

If we try to access a local variable outside its scope, an error will be thrown.

def func1():
    x = 10

func1()
print(x)
Output
Traceback (most recent call last):
  File "<stdin>", line 5, in
NameError: name 'x' is not defined

The variable x is a local variable which is created inside the func1 function and therefore can be accessed only within the function. We got the error because we tried to print the variable outside its local scope.

Python Global Variables


Variables that are defined outside of all the functions and are accessible throughout the program are called global variables and are said to have global scope. Once declared, these can be accessed by any function in the program.

An example of a global variable is given below.

x = 10  # global variable

def func():
    print("Inside func", x)

func()
print("Outside func", x)
Output
Inside func 10
Outside func 10

Here, x is a global variable because it is declared outside of the function. Thus unlike local variables which can only be used in the function in which they are declared, x can be used throughout the program and can be used in all the functions in the program.

Let’s see what happens when we change the value of a global variable inside a function.

x = 10  # global variable

def func():
    x = x + 1
    print("Inside func", x)

func()
print("Outside func", x)
Output
Traceback (most recent call last):
  File "script.py", line 7, in <module>
    func()
  File "script.py", line 4, in func
    x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment

We got the UnboundLocalError error because Python considers x in x + 1 as a local variable and we have not assigned any value to this local variable inside the function.

So, to change the value of a global variable inside a function, we first need to declare that variable as global using the global keyword.

x = 10  # global variable

def func():
    global x  # declaring that x is global variable
    x = x + 1
    print("Inside func", x)

func()
print("Outside func", x)
Output
Inside func 11
Outside func 11

Here, writing global x inside the function tells Python that x is a global variable. Thus, incrementing the value of x by 1 inside the function incremented its value to 11.

Let’s see an example where both local and global variables have the same name.

x = 10  # global variable

def func():
    x = 20  # local variable
    print("Inside func", x)

func()
print("Outside func", x)
Output
Inside func 20
Outside func 10

In this example, we used the same name x for local and global variables. The variable x declared inside the function is a local variable and has the value 20, whereas the variable x declared outside the function is a global variable and has a value 10.

Python Nonlocal Variables


Nonlocal variables are used in nested functions. 

Suppose a function named outer has a nested function named inner. Then a variable x declared inside the outer function is not a local variable for the inner function. In this case, this variable x is said to be a nonlocal variable for the inner function.

To understand how to access nonlocal variables, look at the following example.

def outer():
    x = 10  # local variable
    def inner():
        print("Inside inner func", x)
    inner()
    print("Inside outer func", x)

outer()
Output
Inside inner func 10
Inside outer func 10

A function named outer has a nested function named inner which is called inside the outer function. A variable x is defined with a value 10 inside the outer function. Its value is printed inside the outer and the inner functions.

Now, let’s try to change the value of the variable x defined inside the outer function in the inner function.

def outer():
    x = 10  # local variable
    def inner():
        x = x + 1
        print("Inside inner func", x)
    inner()
    print("Inside outer func", x)

outer()
Output
Traceback (most recent call last):   File "script.py", line 9, in <module>
    outer()
  File "script.py", line 6, in outer
    inner()
  File "script.py", line 4, in inner
    x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment

We got the UnboundLocalError error because Python considers x in x + 1 as a local variable of the inner function but it is not assigned any value inside the inner function. In other words, the variable x is local to the outer function but not local to the inner function.

To remove the error and to be able to change the value of the local variable of the outer function inside the inner function, we first need to declare that variable as non local using the nonlocal keyword.

Yes, this is similar to using the global keyword.

def outer():
    x = 10  # local variable
    def inner():
        nonlocal x  # declaring that x is a non local variable
        x = x + 1
        print("Inside inner func", x)
    inner()
    print("Inside outer func", x)

outer()
Output
Inside inner func 11
Inside outer func 11

Writing nonlocal x inside the inner function tells Python that x is not local to the inner function. Thus, incrementing the value of x by 1 inside the inner function incremented its value to 11.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
Nurture your mind with great thoughts. To believe in the heroic makes heroes.
- Benjamin Disraeli


Ask Yours
Recent Posts
asds
asds
jasd
jasd
as
as
Post Yours
Doubt? Ask question