For what purpose “NonLocal” keyword is used in Python?
Hello,
Here is the answer to your query-
First, let’s discuss the local and global scope. By example, a variable defined inside a function is local to that function. Another variable defined outside any other scope is global to the function.
Suppose we have nested functions. We can read a variable in an enclosing scope from inside he inner function, but cannot make a change to it. For that, we must declare it nonlocal inside the function. First, let’s see this without the nonlocal keyword.
>>> def outer():
a=7
def inner():
print(a)
inner()
>>> outer()
7
```` >>> def outer():
a=7
def inner():
print(a)
a+=1
print(a)
inner()
outer()
File “<pyshell#462>”, line 1, in <module>
outer()
File “<pyshell#461>”, line 7, in outer
inner()
File “<pyshell#461>”, line 4, in inner
print(a)
UnboundLocalError: local variable ‘a’ referenced before assignment.
So now, let’s try doing this with the ‘nonlocal’ keyword:
>>> def outer():
a=7
def inner():
nonlocal a
print(a)
a+=1
print(a)```
inner()
outer()