Explain LEGB scope and the `global` / `nonlocal` keywords.
IntermediateConceptLanguage essentials & functions
Answer
Name lookup goes Local, Enclosing (outer functions), Global (module), Built-in. Assigning to a name inside a function makes it local unless declared otherwise.
global xrebinds a module-level name.nonlocal xrebinds a name in the enclosing function (closures).
UnboundLocalError: cannot access local variable 'count' happens when you read then assign a name that exists globally. In real code avoid global; pass state explicitly or use a class.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner