Which fix removes the bug?
def counter():
total = 0
def add(n):
total += n
return total
return add
- Declare
nonlocal totalin add - Declare
global totalin add - Move
total = 0inside add - Return
add()from counter
Assigning to total makes it local to add, so
Play Problem Solving ▸
+= raises UnboundLocalError; nonlocal rebinds the enclosing one.