Interview Prep/Python for DevOps/Language essentials & functions

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 x rebinds a module-level name.
  • nonlocal x rebinds 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.

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions