Python nonlocal Keyword
The Python nonlocal keyword is designed to indicate that a variable within a function that is inside a function, i.e., a nested function is just not local to it, implying that it is located in the outer function.
We must define a non-local parameter with nonlocal keyword if we ever need to change its value under a nested function. Otherwise, the nested function creates a local variable using that title. It is a case-sensitive keyword.
Syntax
Following is a syntax of the Python nonlocal keyword −
nonlocal
Example
Following is a basic syntax of the Python nonlocal keyword −
def function1():
var1 = 200
def function2():
nonlocal var1
var1 = 3
print("The value inside the inner function: ", var1)
function2()
print("The value inside the outer function: ", var1)
function1()
Output
Following is the output of the above code −
The value inside the inner function: 3 The value inside the outer function: 3
Using global and nonlocal variables
When we defined a nonlocal variable and global variable with the same name it will result an SyntaxError.
Example
Here, we have defined a global variable, global_var with Tutotialspoint and the nonlocal variable global_var with Tp which resulted an error as both the variable names are same −
global global_var = "Tutotialspoint"
def funtion1():
def funtion2():
nonlocal global_var
global_var = "Tp"
print("The value of inside function: ", global_var)
funtion2()
print("The value of outside function: ", global_var)
function1()
Output
Following is the output of the above code −
File "/home/cg/root/54869/main.py", line 1
global global_var = "Tutotialspoint"
^
SyntaxError: invalid syntax
Using nonlocal Keyword in Multiple Nested Functions
The nested functions are those functions, in which more than one functions are defined with a single function. The nonlocal keyword is used in a nested function to refer to a variable in the nearest enclosing scope that is not global.
The nonlocal variable allows you to modify a variable defined in an outer (but not global) function scope, enabling the nested function to access and change the value of that variable.
Example
def function():
var1 = 'Welcome to Tutorix'
def function1():
var1= 'Welcome to Tutorialspoint'
def function2():
nonlocal var1
print("The value of nonlocal variable:", var1)
var1 = "Python Tutorials"
print("The value of nonlocal variable: ", var1)
function2()
function1()
print("The value of outside function: ",var1)
function()
Output
Following is the output of the above code −
The value of nonlocal variable: Welcome to Tutorialspoint The value of nonlocal variable: Python Tutorials The value of outside function: Welcome to Tutorix
python_keywords.htm