Nonlocal 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:
123456789101112def 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()
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
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 3.7
Nonlocal Variables in Python: Working with Enclosed Scopes
Desliza para mostrar el menú
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:
123456789101112def 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()
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
¡Gracias por tus comentarios!