The LEGB rule
When Python sees a name in a function, it looks for the binding in four scopes, in order. Local first (the function itself), then Enclosing (any outer function that wraps this one), then Global (the module's top level), then Builtin (len, range, print, and friends).
This is the LEGB rule, and it determines what every name resolves to. The first scope that has a binding wins, the rest are not consulted.
Most confusion about scope comes from accidentally shadowing a builtin (def list(...) is a bad idea) or trying to assign to a global from inside a function (which creates a local instead, unless you use global). The rule is mechanical, but the consequences take a minute to digest.