Introduction
Enclosing scope helps a function remember variables from the function that contains it. This lets you use those variables inside the smaller function without passing them again.
Jump into concepts and practice - no test required
def outer_function(): x = 10 # variable in outer function def inner_function(): print(x) # uses variable from outer function inner_function()
def greet(): message = 'Hello' def say_hello(): print(message) say_hello()
def counter(): count = 0 def increment(): nonlocal count count += 1 print(count) increment() increment()
def outer(): text = 'Hi there' def inner(): print(text) inner() outer()
enclosing scope mean in Python functions?nonlocal keyword.global is for variables at the module level, not enclosing functions.nonlocal keyword inside the inner function -> Option Cdef outer():
x = 5
def inner():
return x + 3
return inner()
print(outer())x is defined in outer() as 5. The inner function returns x + 3, which is 8.outer() calls inner() and returns its result, so print(outer()) prints 8.def outer():
x = 10
def inner():
x = x + 5
return x
return inner()
print(outer())inner(), x = x + 5 tries to modify x. Python treats x as local but it is used before assignment.UnboundLocalError because x is referenced before assignment locally. The fix is to declare nonlocal x.def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
print(c())
print(c())
print(c())counter() function returns increment(), which modifies count using nonlocal. This keeps count persistent across calls.c() increases count by 1 and returns it. So outputs are 1, then 2, then 3.