Functions & Scope · Question 16 · Hard

The enclosing variable x is reassigned after the inner function is defined but before it is called. What does this code print?

def outer():
    x = "first"
    def inner():
        return x
    x = "second"
    return inner

print(outer()())
  1. second
  2. first
  3. NameError
  4. None
Answer and explanation

Answer: A. second

Explanation: A closure remembers the variable, not the value it had when inner was defined. By the time inner runs, x in the enclosing scope is "second", so that is what it returns.

Previous: A function signature mixes normal parameters, *rest and a keyword-only… · Next: A default parameter value refers to a module-level variable that is changed…

Practise functions & scope

Try a fresh set of functions & scope questions with an explanation after every answer, free and without signing up: Functions & Scope practice. Or sit a full placement mock test.

More functions & scope questions

More python practice

Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge