In python, nonlocal keyword is useful to work with the variables inside nested functions. If you want to create a nonlocal variable in the inner function that should already exist in the outside function.
Generally, if you create a variable inside of the function, that variable scope is limited to within that function, but if you create the variable with a
nonlocal keyword that variable scope is neither local nor global.
Following is the example of creating the nonlocal variable inside of the nested function using the
nonlocal keyword in python.
If you observe the above example, we created a nonlocal variable x inside of the add() function using a
When you execute the above python example, you will get the result as shown below.
The changes that we do for nonlocal variables will reflect in local variables. In python, if you try to create a nonlocal variable in the inner functions without existing that variable in outer functions, you will get an exception like no binding for nonlocal ‘x’ found.
Following is the example of creating the nonlocal variables inside of nested function in python.
If you observe the above example, we directly created a nonlocal variable (x) inside of the nested function (add).
When you execute the above python example, you will get an exception like as shown below.
This is how you can use nonlocal variables inside of nested functions to make required changes based on your requirements.