$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · hard · #216

Which fix removes the bug?

def counter():
    total = 0
    def add(n):
        total += n
        return total
    return add
  1. Declare nonlocal total in add
  2. Declare global total in add
  3. Move total = 0 inside add
  4. Return add() from counter
Assigning to total makes it local to add, so += raises UnboundLocalError; nonlocal rebinds the enclosing one.
Play Problem Solving ▸