Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Nonlocal Variable | Variable Scope
Intermediate Python: Arguments, Scopes and Decorators
course content

Conteúdo do Curso

Intermediate Python: Arguments, Scopes and Decorators

Intermediate Python: Arguments, Scopes and Decorators

1. Packing and Unpacking
2. Arguments in Function
3. Function as an Argument
4. Variable Scope
5. Decorators

Nonlocal Variable

So, now we understand the difference between global and local variables and have learned about nested functions. The <strong>nonlocal</strong> 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 <strong>nonlocal</strong>.

The output is:

Tudo estava claro?

Seção 4. Capítulo 5
We're sorry to hear that something went wrong. What happened?
some-alt