Python Tutorial · Functions · Lesson 26 of 42
Python Scope
Local, enclosing, global and built-in scope (LEGB), global and nonlocal.
Local and global
A variable created inside a function is local to it. Variables created at the top level of a file are global.
x = "global"
def show():
x = "local"
print("inside:", x)
show()
print("outside:", x)
Output
inside: local outside: global
Python looks names up in order: Local → Enclosing function → Global → Built-in (the LEGB rule).
Changing outer variables
Assigning inside a function creates a new local variable. To change a global, declare it with global; to change a variable from an enclosing function, use nonlocal.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)
def make_counter():
n = 0
def step():
nonlocal n
n += 1
return n
return step
counter = make_counter()
counter()
print(counter())
Output
2 2
Prefer returning values over modifying globals — it keeps functions predictable.
Closures
An inner function remembers the variables of the function that created it:
def multiplier(factor):
def multiply(x):
return x * factor
return multiply
double = multiplier(2)
triple = multiplier(3)
print(double(5), triple(5))
Output
10 15
Test yourself
Which keyword lets an inner function reassign a variable of its enclosing function?
globalnonlocalouterstatic
Show answer
Answer: nonlocal