top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use nonlocal keyword in python?please explain with example?

+3 votes
1,607 views
What is the use nonlocal keyword in python?please explain with example?
posted Feb 3, 2015 by Gnanendra Reddy

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
 
Best answer

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope.

See the following examples without and with nonlocal

>>> def outer():
       x = 1
       def inner():
           x = 2
           print("inner:", x)
       inner()
       print("outer:", x)

>>> outer()
inner: 2
outer: 1

To this, using nonlocal:

>>> def outer():
       x = 1
       def inner():
           nonlocal x
           x = 2
           print("inner:", x)
       inner()
       print("outer:", x)

>>> outer()
inner: 2
outer: 2
answer Feb 3, 2015 by Salil Agrawal
...