Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is the difference between the global and nonlocal keywords in Python?

SHORT ANSWER

global makes a name inside a function refer to the module-level variable. nonlocal makes it refer to a variable in the nearest enclosing function. Both are needed only when you assign to the name, not when you just read it.

Explain it simply

Without these keywords, assigning to a name inside a function creates a fresh local one, like writing in your own notebook. global says "use the notice board of the whole school". nonlocal says "use the notebook of the class I am nested inside".

Example

python
count = 0

def bump():
    global count
    count += 1

bump(); bump()
print(count)       # Output: 2

def make_counter():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc

c = make_counter()
print(c(), c(), c())   # Output: 1 2 3

nonlocal is what makes closures able to keep and update state between calls. It cannot reach module-level names, and the target must already exist in an enclosing function.

What to say in the interview

"global binds a name to the module scope, nonlocal to the nearest enclosing function scope. I only need them for assignment; reading outer variables works automatically. I try to avoid global state and prefer passing arguments and returning values."

Common mistakes

  • Using nonlocal for a module-level variable, which is a SyntaxError.

#python#functions#scope

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.