In Python, a variable declared inside a function is a local variable and is only accessible within the function's scope. However, if you need to access or modify a variable defined in an outer function, you can use the nonlocal keyword.
A nonlocal variable is a variable that is defined in an outer function and is accessed or modified by an inner function. The nonlocal keyword tells Python that a variable is not local to the current function but belongs to an outer function's scope.
Here's an example of a nonlocal variable in Python:
def outer_function(): x = 10 def inner_function(): nonlocal x x += 5 print("x in inner function:", x) inner_function() print("x in outer function:", x)outer_function() |
In the above example, outer_function defines a local variable x with a value of 10. inner_function modifies the x variable using the nonlocal keyword, adding 5 to its value. The outer_function then prints the value of x after it has been modified by inner_function.
The output of the above code will be:
x in inner function: 15x in outer function: 15 |
The nonlocal keyword is useful when you need to share data between multiple functions or want to modify a variable defined in an outer function. However, it's important to use it sparingly and with care, as it can make code more complex and harder to understand.