How to declare a nonlocal variable in Python

A nonlocal variable binds its value to a variable of the same name in the nearest block of lesser indentation. Nonlocal variables do not affect global variables. For example, declaring a nonlocal variable var will bind the value of var to a variable named var in the nearest outer scope.

Solution for How to declare a nonlocal variable in Python : You can use the keyword nonlocal to declare a nonlocal variable Use the syntax nonlocal var to declare a nonlocal variable var.

In the code sample above, calling inner_function() changes the value of var to “inner”, but only within outer_function().


how-to-declare-a-nonlocal-variable-in-python