Nested Functions and Non Local Variables in Python

In this class, we discuss Nested Functions and Non Local Variables in Python.

For Complete YouTube Video: Click Here

Nested Functions

The reader should have prior knowledge of local and global variables in python. Click here.

Let’s take an example and understand the concept.

First, we refresh the concept of a local and global variable.

a=1
def f():
    global a
    a=5
    print("local variable")
    print(a)
f()
print("global variable")
print(a)
Output:
local variable
5
global variable
5

In the above program, we defined a global variable a.

If we want to assign a new value to the global variable a, in the function f., we use the keyword global.

In the function, we defined global a. this statement allows the function not to create local variable a.

Nested Functions:

Function within the function we call nested function.

Example 1

a=1
def f():
    b=6
    c=7
    def f1():
        d=40
        print("global value inside nested function",a)
        print(" value from above function",b)
        print("local value of nested function",d)
        nonlocal c
        c=20
    f1()
    print(" non local updated value",c)
    print(b)
    # d is local to f1

f()
print(a)

Output:
global value inside nested function 1
value from above function 6
local value of nested function 40
non local updated value 20
6
1

In the above program, a is a global variable.

We had a function f1 inside the function f.

Variables b and c are defined within function f. we can use variables b and c inside function f anywhere. I.e., in the function, f1 too.

Variable d is defined inside function f1. Variable d is local to function f1.ie we can not use outside the function f1.

In function f1, we defined nonlocal c. meaning, should take the variable c from function f.

Do not create a new local variable in function f1.

Now function f1 considers variable c as a nonlocal variable.

This nonlocal keyword is used similar to the global keyword used in our first example.

The variable d, local to the f1 function, can not be used inside function f.

With this knowledge, analyze the program output given above.

Suppose function f tries to use the variable d. It will get an error. It was shown in the program below.

Example 2

a=1
def f():
    b=6
    c=7
    def f1():
        d=40
        print("global value inside nested function",a)
        print(" value from above function",b)
        print("local value of nested function",d)
        nonlocal c
        c=20
    f1()
    print(" non local updated value",c)
    print(b)
    print(d)
    # d is local to f1
f()
print(a)

Name error is shown in the output.