Python difference between global statement and nonlocal statement

Here we will see some differences between the global statement and the nonlocal statement. If you you have no idea what global statement or nonlocal statement means visit the links given blow.

Link : Python global statement
link : Python nonlocal statement


i)Global statement permits modification of global variable in local scope and nonlocal statement permits modification of enclosing scope variable in local scope.

To modify the global variable in a local scope we must declare the variable with the global statement first. Similarly, if we wish to modify the enclosing scope variable ( or nested scope variable) in a local scope, we should declare it with the nonlocal statement first.

The nonlocal statement does to enclosing scope variable what global statement does to the global variable. The nonlocal is a counterpat of the global statement.

Python difference between global statement nonlocal statement

Afer calling func() the value of ‘gb’ and ‘esv’ are changed even outisde the local scope.



ii)Names declared with nonlocal must pre-exist but global can be declared with new names

The global statement can be declared with existing global variables or new variables, but the nonlocal statement is limited to only pre-existing variable.

>>> gb=9900
>>> def func():
...  ns=10
...  def foo():
...   global gb #work fine 
...   global gb1 #work fine
...   nonlocal ns #Work fine
...   nonlocal nl
...

The last statement ‘nonlocal nl‘ is an error, since nl does not pre-exist. If you run the code you will get the message “SyntaxError: no binding for nonlocal ‘nl’ found”.




Leave a Reply

Your email address will not be published. Required fields are marked *