Home >>Python Keywords >Python nonlocal Keyword

Python nonlocal Keyword

Python nonlocal Keyword

Python nonlocal keyword is a case-sensitive and they are usually used in nested functions, where the variable should not belong to the inner function which is declared in outer function.

Here is an example of Python nonlocal Keyword:


def func1():
z = "John"
def func2():
nonlocal z
z = "hello phptpoint"
func2() 
return z
print(func1())

Output:
hello phptpoint

Example 2:


def outerfunc():
x = 15
y = 25
def innerfunc():
    nonlocal a
    x = 50
    y = 150  
innerfunc()
print("x : ", x)
print("y : ", y)
outerfunc()

Output:
x : 50
y : 25

No Sidebar ads