Scope & Closures Questions with Answers

32 practice questions on Scope & Closures (Python) with answers and step-by-step solutions. Try 10 samples below, then practise all 32 free in the AptiNest app.

Sample questions

Question 1Easy

What is the output?

def f():
    return y * 2

y = 4
print(f())
  1. 8
  2. NameError
  3. 4
  4. 0

Answer: A. 8

Explanation

y is defined before f is called, and since f does not assign y, the name is looked up in the global scope.

Step-by-step solution

  1. y is a global defined before f() is called.
  2. f does not assign y, so it reads the global.
  3. 4*2 = 8.

Why the other options are wrong

  • B. y exists by the call time.
  • C. The function doubles y.
  • D. y is 4, not 0.

Tip: Define before call.

Question 2Easy

What is the output?

def f():
    z = 10
    return z

f()
print("z" in dir())
  1. NameError
  2. False
  3. 10
  4. True

Answer: B. False

Explanation

z is local to f and disappears when f returns; dir() at module level lists only module-level names.

Step-by-step solution

  1. z = 10 is a local variable inside f, so it is not a module-level name.
  2. f() returns and its local names are gone.
  3. dir() at module level lists only module names, and "z" is not one of them.
  4. So "z" in dir() is False, which is option B.

Why the other options are wrong

  • A. No NameError happens; the test is just a membership check on a list of strings.
  • C. The value 10 is never printed; the code prints a boolean.
  • D. Z is local to f, so it is not in the module's dir() list.

Tip: Locals inside a function are not visible in dir() or globals() at module level.

Question 3Easy

What is the output?

total = 10

def add(n):
    global total
    total += n

add(5)
add(1)
print(total)
  1. 16
  2. 11
  3. 10
  4. UnboundLocalError

Answer: A. 16

Explanation

The global declaration makes total refer to the module variable, so both calls update it: 10 + 5 + 1 = 16.

Step-by-step solution

  1. The global statement makes total refer to the module variable.
  2. add(5) changes total from 10 to 15.
  3. add(1) changes it from 15 to 16.
  4. The output is 16.

Why the other options are wrong

  • B. Both calls change total, so 11 would skip the add(5) call.
  • C. The module variable is updated by both calls, so it is not 10.
  • D. Global makes the name refer to the module variable, so no error is raised.

Tip: Use global to rebind a module-level name inside a function.

Question 4Easy

What is the output?

x = 1
def f():
    global x
    x = 2
    y = 3
f()
print(x, "y" in globals())
  1. 2 False
  2. 1 False
  3. NameError
  4. 2 True

Answer: A. 2 False

Explanation

global x makes the assignment update the module variable; y is an ordinary local and never appears in globals().

Step-by-step solution

  1. Global x makes f's assignment change the module variable x to 2.
  2. y = 3 creates a local y in f, not a module variable.
  3. Print shows x as 2 and checks whether y is in globals(), which is False.
  4. The output is 2 False.

Why the other options are wrong

  • B. The global x was set to 2 by f, so it is not 1.
  • C. globals() exists and the name lookup is valid, so no NameError occurs.
  • D. Y is local to f, so it is not in globals(), which makes the second value False.

Tip: Only names declared global are changed at module level; other assignments stay local.

Question 5Medium

What is the output?

x = "global"

def outer():
    x = "enclosing"
    def inner():
        return x
    x = "changed"
    return inner

print(outer()())
  1. enclosing
  2. NameError
  3. global
  4. changed

Answer: D. changed

Explanation

Closures capture variables, not values. inner looks up x when it is called, and by then the enclosing x has been rebound to "changed".

Step-by-step solution

  1. Outer sets x to enclosing, defines inner, then rebinds x to changed.
  2. Inner does not read x until it is called.
  3. When outer()() runs, inner finds the enclosing x, which is now changed.
  4. The output is changed.

Why the other options are wrong

  • A. The closure looks up x when called, after the rebinding, so it is not enclosing.
  • B. X is defined in the enclosing function, so no error is raised.
  • C. Inner reads the enclosing x, not the global one.

Tip: Closures look up variables when called, so later rebinding is seen.

Question 6Medium

What happens when this code runs?

count = 0

def bump():
    count += 1
    return count

print(bump())
  1. NameError: count is not defined at module level
  2. UnboundLocalError is raised
  3. 1 is printed
  4. 0 is printed

Answer: B. UnboundLocalError is raised

Explanation

Because count is assigned inside bump, it is treated as local for the whole function; reading it in count += 1 before assignment raises UnboundLocalError.

Step-by-step solution

  1. Count += 1 inside bump makes count a local name for the whole function.
  2. The += reads count before any local value is assigned.
  3. Python raises UnboundLocalError at that read.
  4. So the answer is UnboundLocalError is raised.

Why the other options are wrong

  • A. The module-level count exists; the error is about the local name inside the function.
  • C. The function fails before it can return 1.
  • D. The function never returns 0, because the error happens first.

Tip: Assigning to a name anywhere in a function makes it local for the whole function; use global or nonlocal to change an outer one.

Question 7Medium

What is the output?

def power(n):
    def raise_to(x):
        return x ** n
    return raise_to

sq, cube = power(2), power(3)
print(sq(4), cube(2))
  1. 16 8
  2. 64 8
  3. 16 16
  4. 8 16

Answer: A. 16 8

Explanation

Each call to power creates a closure with its own n: sq uses n=2 (4**2 = 16)
and cube uses n=3 (2**3 = 8).

Step-by-step solution

  1. power(2) creates raise_to with n = 2; power(3) creates another with n = 3.
  2. sq(4) computes 4 2 = 16.
  3. cube(2) computes 2 3 = 8.
  4. The printed output is 16 8, which is option A.

Why the other options are wrong

  • B. Sq uses n = 2, so 4 2 is 16, not 64 (that would be 4 3).
  • C. Cube uses n = 3, so the second value is 8, not 16.
  • D. The two values are swapped; sq(4) is 16 and cube(2) is 8.

Tip: Each call to an outer function makes a separate closure, so the values it captures do not mix.

Question 8Medium

What is the output?

def counter():
    count = [0]
    def inc():
        count[0] += 1
        return count[0]
    return inc

c = counter()
c(); c()
print(c())
  1. 1
  2. UnboundLocalError
  3. 3
  4. 0

Answer: C. 3

Explanation

count[0] += 1 mutates the list rather than rebinding count, so no nonlocal declaration is needed; three calls give 3.

Step-by-step solution

  1. counter() makes a list count = [0] and returns the inner function inc.
  2. c() runs twice, changing count[0] from 0 to 1 and then to 2.
  3. The third call, print(c()), changes count[0] to 3 and returns 3.
  4. The printed output is 3, which is option C.

Why the other options are wrong

  • A. The value 1 is only after the first call; the third call gives 3.
  • B. count[0] += 1 changes the list, not the name, so no error happens.
  • D. The count starts at 0 but is increased before it is returned, so the result is 3.

Tip: Changing an item of a mutable list in a closure works without nonlocal; rebinding the name needs nonlocal.

Question 9Hard

What is the output?

def make():
    funcs = []
    for i in range(3):
        def f(i=i):
            return i
        funcs.append(f)
    i = 99
    return [g() for g in funcs], funcs[0](7)

print(make())
  1. ([2, 2, 2], 7)
  2. ([0, 1, 2], 7)
  3. ([0, 1, 2], 0)
  4. ([99, 99, 99], 7)

Answer: B. ([0, 1, 2], 7)

Explanation

The defaults captured the values 0, 1, 2 at definition time, so rebinding i later has no effect; an explicit argument overrides the default.

Step-by-step solution

  1. The loop makes three functions; each default i=i captures 0, 1 and 2.
  2. Later i = 99 only changes the local name, so the stored defaults stay the same.
  3. [g() for g in funcs] calls each with no argument, giving [0, 1, 2].
  4. The first function called with 7 returns 7, because the explicit argument overrides the default.
  5. The output is ([0, 1, 2], 7), which is option B.

Why the other options are wrong

  • A. The defaults were captured at each loop step, so the values are 0, 1, 2, not 2, 2, 2.
  • C. An explicit argument of 7 overrides the default, so the second value is 7, not 0.
  • D. The defaults were captured before i = 99, so 99 is never returned.

Tip: Default arguments are evaluated once, when the def runs; use i=i to capture a loop variable.

Question 10Hard

What is the output?

def make():
    data = []
    def add(x):
        data.append(x)
        return len(data)
    return add

add = make()
add("a")
print(add("b"), add.__closure__[0].cell_contents)
  1. UnboundLocalError
  2. 2 []
  3. 2 ['a', 'b']
  4. 1 ['b']

Answer: C. 2 ['a', 'b']

Explanation

data is never reassigned, only mutated, so nonlocal is not needed. The closure cell holds the same list, which now contains both items.

Step-by-step solution

  1. Add refers to data, which is created once in make and never rebound.
  2. add('a') appends a to data; add('b') appends b, and returns the length 2.
  3. The closure cell holds the same list, which now reads ['a', 'b'].
  4. The output is 2 ['a', 'b'].

Why the other options are wrong

  • A. Mutating data needs no nonlocal, so no UnboundLocalError happens.
  • B. The list has both items, so it is not empty.
  • D. Both calls appended to the same list, so it holds two items and the length is 2.

Tip: A closure can change a mutable object it captures without nonlocal; nonlocal is needed only to rebind.

Practise all 32 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Python topics · All topics