Introduction to Variable Scope in Python
This article explains Python's four variable scope types—local, enclosing, global, and built‑in—through clear descriptions and runnable code examples that illustrate how each scope affects variable accessibility and program behavior.
In Python, a variable's scope determines where it can be accessed, and there are four main scope types: local, enclosing, global, and built‑in.
1. Local Scope
def local_scope():x = 10print(x) # Output: 10local_scope()print(x) # Error: NameError: name 'x' is not defined2. Global Scope
y = 20def global_scope():print(y) # Output: 20global_scope()print(y) # Output: 203. Modifying Global Variables
z = 30def modify_global():global zz = 40print(z) # Output: 40modify_global()print(z) # Output: 404. Enclosing (Non‑local) Scope
def outer():a = 50def inner():nonlocal aa = 60print(a) # Output: 60inner()print(a) # Output: 60outer()5. Built‑in Scope
def built_in_scope():print(len("hello")) # Output: 5built_in_scope()6. Local vs Global Name Collision
b = 70def shadow_variable():b = 80print(b) # Output: 80shadow_variable()print(b) # Output: 707. Nested Function Local Variable
def outer_function():c = 90def inner_function():c = 100print(c) # Output: 100inner_function()print(c) # Output: 90outer_function()8. Using globals() Function
d = 110def use_globals():print(globals()['d']) # Output: 110use_globals()9. Function Parameter vs Local Variable
def func_param(e):e = 120print(e) # Output: 120func_param(130)10. Default Parameter Value with Global Variable
f = 140def default_param(g=f):print(g) # Output: 140default_param()Understanding these scope rules helps write more efficient and error‑free Python code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
