Python nonlocal Keyword
Example
Create a function inside a function that uses the variable x as a nonlocal variable:
def myfunc1(): x = "Bill" def myfunc2(): nonlocal x x = "hello" myfunc2() return x print(myfunc1())
Definition and Usage
The nonlocal keyword is used to use variables within nested functions, where the variables should not belong to the inner function.
Please use the keyword nonlocal to declare a variable that is not a local variable.
More Examples
Example
As in the above example, but without using the nonlocal keyword:
def myfunc1(): x = "Bill" def myfunc2(): x = "hello" myfunc2() return x print(myfunc1())
Related Pages
Keyword global Used to create global variables.