Scope

When you use a name, Python looks for it in four places, in order: Local (this function), Enclosing (any outer function), Global (this module), Builtins (len, print). That is the LEGB rule.

Reading an outer name just works. Assigning to a name makes it local to the function, for the whole function. So this fails:

count = 0
def bump():
    count += 1  # UnboundLocalError

count += 1 assigns, so count is local, and it has no value yet when Python tries to read it. This is a favourite interview puzzle.

  • global count says "assign to the module's count".
  • nonlocal count says "assign to the enclosing function's count".

Use them sparingly. Returning a value is usually clearer than changing a global.

Run it, then remove the global line to see the error.