Category: python
Using global
Published on 27 Oct 2026
Explanation
global declares that assignment in a function targets a module-level name.
Code:
count = 0
def increment():
global count
count += 1
increment()
print(count)
Explanation
A name assigned inside a function is local by default; reading it before assignment can raise UnboundLocalError.
Code:
count = 10
def update():
# print(count); count = 20 # UnboundLocalError
pass
update()
print(count)
Explanation
nonlocal allows a nested function to reassign an existing variable in an enclosing function scope.
Code:
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
print(count)
outer()
Explanation
global targets module scope; nonlocal targets an enclosing function scope.
Code:
value = 100
def outer():
value = 10
def inner():
nonlocal value
value += 5
inner()
print(value)
outer()
Explanation
A closure can preserve state between calls without using a global variable.
Code:
def counter_factory():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter_factory()
print(c(), c())