Scope: local, global, nonlocal
Names are looked up local, enclosing, global then built in. Use global or nonlocal to rebind outer names, though returning values is cleaner.
Example
count = 0
def inc():
global count
count += 1
inc(); inc()
print(count)
def outer():
n = 0
def inner():
nonlocal n
n += 1
inner(); return n
print(outer())Result
2 1
Exercise
Rebind a global.
countQuiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.