Python nonlocal Keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function.

Example

Python
def outer():
    x = "John"

    def inner():
        nonlocal x  # we want to use the outer function's x variable
        x = "hello"
  
    inner()

    return x

outerx = outer()
print('The inner function has changed x to:', outerx)

Output

The inner function has changed x to: hello