Home »
Python
nonlocal keyword with example in Python
Python nonlocal keyword: Here, we are going to learn about the nonlocal keyword with example.
Submitted by IncludeHelp, on April 15, 2019
Python nonlocal keyword
nonlocal is a keyword (case-sensitive) in python, it is used when we work with the nested functions and we need to use a function which is declared in outer function, if we do the same, a variable will be created as local and we then we will not be able to work with a variable in inner function which is declared in outer function.
In such a case, we can define the variable (which is declared in outer function) as a nonlocal variable in inner function using nonlocal keyword.
Syntax of nonlocal keyword
nonlocal variable_name
Example:
def outerfunc():
a = 10
def innerfunc():
# nonlocal binding
nonlocal a
a = 100
# calling inner function
innerfunc()
# printing the value of a
print("a : ", a)
Output:
a : 100
Python examples of nonlocal keyword
Example 1: Define two variables in outer function and make one variable as nonlocal in inner function.
# python code to demonstrate an example
# of nonlocal keyword
# nested functions
def outerfunc():
a = 10
b = 20
def innerfunc():
# nonlocal binding
nonlocal a
a = 100 # will update
b = 200 # will not update,
# it will be considered as a local variable
# calling inner function
innerfunc()
# printing the value of a and b
print("a : ", a)
print("b : ", b)
# main code
# calling the function i.e. outerfunc()
outerfunc()
Output
a : 100
b : 20
As you see in the output, a and b are the variables of outerfunc() and in the innerfunc() we are binding variable a as local, thus a will not be local here but, b will be considered as local variable for innerfunc() and if we change the value of b that will be considered a new assigned for local variable(for innerfunc()) b.