Python Scope & Lifetime
In this page:
Local Scope
A variable created inside a function exists only in that function's local scope — it's created when the function starts running and destroyed when it returns, invisible to any code outside that function.
Example: Local Scope
def greet():
message = "Hello"
print(message)
greet()
Global Scope
Variables assigned at the top level of a script, outside any function, live in the global scope and can be *read* from inside any function without any special syntax — only *reassigning* them requires extra steps.
Example: Global Scope
count = 10
def show():
print(count)
show()
The global Keyword
Attempting to assign to a global variable's name inside a function normally creates a new local variable instead of touching the outer one; declaring it with the global keyword first tells Python you intend to modify the actual outer variable.
Example: The global Keyword
count = 0
def increment():
global count
count += 1
increment()
print(count)
Nonlocal Scope
In a function nested inside another function, nonlocal lets the inner function modify a variable belonging to the enclosing (but not global) function's scope — distinct from global, which only reaches all the way out to module level.
Example: Nonlocal Scope
def outer():
value = 1
def inner():
nonlocal value
value += 1
inner()
print(value)
outer()
Built-in Scope
Built-in names like print(), len(), and int() live in Python's built-in scope, the outermost layer checked last, which is why you can call them from literally anywhere without importing or defining them yourself.
Example: Built-in Scope
print(len("hello"))
print(int("42"))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: