python icon

Variables & Scoping Rules

Expert Answer & Key Takeaways

Mastering Variables & Scoping Rules is essential for high-fidelity technical performance and advanced exam competency in 2026.

Python Variables & Scoping Rules: The LEGB Rule

Python resolves variable names using the LEGB rule (Local, Enclosing, Global, Built-in), determining where a variable can be accessed or modified within a script.

1. The Proof Code

# Global Scope counter: int = 0 def outer_function() -> None: # Enclosing Scope text: str = "Initial" def inner_function() -> None: # Local Scope nonlocal text global counter text = "Modified by Inner" counter += 1 print(f"Local access: {text}, Global access: {counter}") inner_function() print(f"Enclosing after inner: {text}") if __name__ == "__main__": outer_function() print(f"Final Global counter: {counter}") # Output: # Local access: Modified by Inner, Global access: 1 # Enclosing after inner: Modified by Inner # Final Global counter: 1

2. Execution Breakdown

  1. Local Scope: Variables defined inside a function. text in inner_function would be local unless explicitly declared otherwise.
  2. Enclosing Scope: Variables in the local scope of outer functions (relevant for nested functions).
  3. Global Scope: Variables defined at the top level of a module or declared global inside a function.
  4. Built-in Scope: Reserved names like len, print, and ValueError provided by Python automatically.
  5. Keywords: The global keyword allows modification of variables in the module-level scope; nonlocal allows modification of variables in the nearest enclosing (non-global) scope.

3. Detailed Theory

Python's scoping is determined by where you assign a variable, not where you first use it. This is a common source of bugs for developers coming from languages like JavaScript or C++.

The LEGB Hierarchy

  • L (Local): Names assigned in any way within a function (def or lambda), and not declared global in that function.
  • E (Enclosing): Names in the local scope of any and all enclosing functions, from inner to outer.
  • G (Global): Names assigned at the top-level of a module file, or declared global in a def within the file.
  • B (Built-in): Names preassigned in the built-in names module: open, range, SyntaxError, etc.

Name Resolution vs. Assignment

When you read a variable, Python searches L -> E -> G -> B. When you assign a variable, Python creates a local name by default unless you use global or nonlocal.
[!TIP] Senior Secret: Minimize the use of global. It makes functions 'impure' and difficult to test because they depend on external state. Instead, pass the global variable as an argument and return the updated value.

Top Interview Questions

?Interview Question

Q:What is the difference between global and nonlocal?
A:
global is used to access or modify variables at the module (top) level. nonlocal is used in nested functions to modify variables in the outer function's scope, but not the global scope.

?Interview Question

Q:What happens if you try to modify a global variable inside a function without the 'global' keyword?
A:
Python will treat the assignment as the creation of a new local variable with the same name, leaving the global variable unchanged (this is called 'shadowing').

Course4All Engineering Team

Verified Expert

Data Science & Backend Engineers

The Python curriculum is designed by backend specialists and data engineers to cover everything from basic logic to advanced automation and API design.

Pattern: 2026 Ready
Updated: Weekly