How do I use the `nonlocal` keyword

The `nonlocal` keyword in Python is used to declare that a variable inside a nested function is not local to that function, but belongs to an enclosing scope. This allows you to modify variables defined in an outer function from within an inner function.
nonlocal keyword, Python, nested functions, variable scope
def outer_function():
    x = "Hello"
    
    def inner_function():
        nonlocal x
        x = "Hello, World!"
    
    inner_function()
    return x

result = outer_function()
print(result)  # Output: Hello, World!
        

nonlocal keyword Python nested functions variable scope