Variable Scope
Local, global, nonlocal scope
Interview Relevant: Common interview topic
Variable Scope
Understanding variable visibility and lifetime.
Code Examples
Variable scope rules.
python
1# Local scope
2def func():
3 x = 10 # Local variable
4 print(x)
5
6# Global scope
7count = 0
8
9def increment():
10 global count # Modify global
11 count += 1
12
13# nonlocal (nested functions)
14def outer():
15 x = 10
16 def inner():
17 nonlocal x # Modify enclosing
18 x += 1
19 inner()
20 return x # 11
21
22# LEGB rule: Local, Enclosing, Global, Built-in
23x = "global"
24def outer():
25 x = "enclosing"
26 def inner():
27 x = "local"
28 print(x) # local
29 inner()