Python Scope & Lifetime
In this page:
global_variable = value
def function_name():
local_variable = value
global global_variable
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" # local variable, only exists inside greet()
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 # global variable, defined outside any function
def show():
print(count) # can read the global variable without any special syntax
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 # declares intent to modify the outer count, not create a local one
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 # refers to outer's value, not the global scope
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"))
- Assigning to a global variable inside a function without
global, which creates a new local variable instead. - Reading a global and then assigning to it in the same function, which raises
UnboundLocalError. - Trying to use a variable defined inside a function from outside it, which raises
NameError.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: