Problem Statement
Explain closures in Python and when to use nonlocal.
Explanation
A closure is a function that captures variables from its enclosing scope, keeping them alive even after the outer function has returned. This enables function factories and configurable behaviors without global state.
Use nonlocal when the inner function needs to rebind a variable from the nearest enclosing scope rather than create a new local variable. This makes stateful callbacks and accumulators straightforward while avoiding mutable defaults or classes for small tasks.
Code Solution
SolutionRead Only
def counter():
count=0
def inc():
nonlocal count
count += 1
return count
return inc
c = counter(); c(); c()