Skip to content
Justice Tech School

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.

 count

Quiz Test

Which finds names in the enclosing function?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.