Python / Core Python Fundamentals Interview Questions
What is variable scope in Python and how does the LEGB rule work?
Scope determines where in the code a variable name is visible and accessible. Python resolves names using the LEGB rule, checking four scopes in order: Local → Enclosing → Global → Built-in.
x = 'global' def outer(): x = 'enclosing' def inner(): x = 'local' print(x) # local inner() print(x) # enclosing outer() print(x) # global
L – Local: names assigned inside the current function.
E – Enclosing: names in any enclosing (outer) function's scope — relevant for nested functions and closures.
G – Global: names assigned at the module's top level.
B – Built-in: names built into Python itself — len, print, range, etc.
To assign to a global variable from inside a function, declare it with global name. To assign to an enclosing-scope variable, use nonlocal name (Python 3+). Without these declarations, Python creates a new local variable instead of modifying the outer one, which is a very common source of bugs in interviews.
count = 0 def increment(): global count count += 1 increment() print(count) # 1
More Related questions...