Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
Python looks up names in Local, Enclosing, Global and Built-in scope order (LEGB); assigning to a name makes it local unless you declare it global or nonlocal.
When code reads a name, Python searches the current function, then enclosing functions, then the module, then built-ins. Any assignment inside a function makes that name local for the whole function, which is why reading a module variable and then assigning to it raises UnboundLocalError. global x lets a function rebind a module-level name, and nonlocal x lets a nested function rebind a name from its enclosing function, which is useful for counters in closures. Heavy use of global usually signals a design that should pass values explicitly or use a class.