Fundamentals 4 min read

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.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Introduction to Variable Scope in Python

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 = 10
print(x)  # Output: 10
local_scope()
print(x)     # Error: NameError: name 'x' is not defined

2. Global Scope

y = 20
def global_scope():
print(y)  # Output: 20
global_scope()
print(y)     # Output: 20

3. Modifying Global Variables

z = 30
def modify_global():
global z
z = 40
print(z)  # Output: 40
modify_global()
print(z)     # Output: 40

4. Enclosing (Non‑local) Scope

def outer():
a = 50
def inner():
nonlocal a
a = 60
print(a)  # Output: 60
inner()
print(a)     # Output: 60
outer()

5. Built‑in Scope

def built_in_scope():
print(len("hello"))  # Output: 5
built_in_scope()

6. Local vs Global Name Collision

b = 70
def shadow_variable():
b = 80
print(b)  # Output: 80
shadow_variable()
print(b)     # Output: 70

7. Nested Function Local Variable

def outer_function():
c = 90
def inner_function():
c = 100
print(c)  # Output: 100
inner_function()
print(c)     # Output: 90
outer_function()

8. Using globals() Function

d = 110
def use_globals():
print(globals()['d'])  # Output: 110
use_globals()

9. Function Parameter vs Local Variable

def func_param(e):
e = 120
print(e)  # Output: 120
func_param(130)

10. Default Parameter Value with Global Variable

f = 140
def default_param(g=f):
print(g)  # Output: 140
default_param()

Understanding these scope rules helps write more efficient and error‑free Python code.

pythoncode examplesProgramming Fundamentalsvariable scope
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.