Nested Functions and Non Local Variables in Python || Lesson 33 || Python || Learning Monkey ||

preview_player
Показать описание
#python#learningmonkey#pythoncoding#placements#pythontutorials#pythoncourse#pythonforbeginners#pythonfordatascience#pythonfullcourse#pythonprogramming#pythonfreecourse
Nested Functions and Non Local Variables in Python
In this class, we discuss Nested Functions and Non Local Variables in Python.
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)

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)

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.
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)

Link for playlists:

Рекомендации по теме
Комментарии
Автор

I've watched 7 other videos and this was the best. Very easy to understand as you walked through it. Thank you.

christinacamps
Автор

Very clear explanation, Thank you Raghuveer

gupthachodisetty
Автор

Sir I have doubt outer function assign argument after that inner function add the above arguments after outer function we have to add +5 in the inner function value how can we implement

saranran
Автор

why a is updating global space. please explain

sayantanbanerjee