Programming FundamentalsNot Started
Scope & Namespaces
Where variables live and how Python looks them up (LEGB rule)
0%
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Scope determines where a variable is accessible. Python uses the LEGB rule to look up names:
- 1Local — inside the current function
- 2Enclosing — in any enclosing functions (closures)
- 3Global — at the module level
- 4Built-in — Python's built-in names (len, print, etc.)
Variables created inside a function are local — they don't exist outside. Global variables exist at module level and can be read (but not written) inside functions without the global keyword.
Understanding scope is critical for Flask decorators, closures, and avoiding hard-to-find bugs.
Examples
Local vs global
Local variables shadow globals inside functions
x = 10 # global
def show():
x = 99 # local — shadows global
print(x) # 99
show()
print(x) # 10 — global unchangedNext in Programming Fundamentals
Recursion