Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Nonlocal Variables in Python: Working with Enclosed Scopes | Understanding Variable Scope in Python
Intermediate Python Techniques

bookNonlocal Variables in Python: Working with Enclosed Scopes

So, now we understand the difference between global and local variables and have learned about nested functions. The nonlocal variable is used in nested functions. Let's look at an example:

123456789101112
def outer_function(): outer_var = 10 def inner_function(): nonlocal outer_var outer_var += 5 print("Nonlocal variable in inner function:", outer_var) inner_function() print("Nonlocal variable in outer function:", outer_var) outer_function()
copy

Just as with global variables, we cannot change the variable created in outer_function inside inner_function without using the special keyword nonlocal.

The output is:

Nonlocal variable in inner function: 15
Nonlocal variable in outer function: 15

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 5

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Awesome!

Completion rate improved to 3.7

bookNonlocal Variables in Python: Working with Enclosed Scopes

Veeg om het menu te tonen

So, now we understand the difference between global and local variables and have learned about nested functions. The nonlocal variable is used in nested functions. Let's look at an example:

123456789101112
def outer_function(): outer_var = 10 def inner_function(): nonlocal outer_var outer_var += 5 print("Nonlocal variable in inner function:", outer_var) inner_function() print("Nonlocal variable in outer function:", outer_var) outer_function()
copy

Just as with global variables, we cannot change the variable created in outer_function inside inner_function without using the special keyword nonlocal.

The output is:

Nonlocal variable in inner function: 15
Nonlocal variable in outer function: 15

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 5
some-alt