ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
x = 1
def outer2():
x = 2
def inner():
print(x)
x = 3
return inner
outer2()()- A. 1
- B. 2
- C. 3
- D. UnboundLocalError
Correct answer: C. 3
inner closes over outer2's local x, not the module-level x. By the time inner actually runs (after outer2() returns the function and it is called), x inside outer2 has been reassigned to 3.
More Python Programming questions
- What is printed? python counters = [] for i in range(3): j = i 2 counters.append(lambda: j) print([c() for c in counters])
- What is printed? python def deco2(f): print("decorating", f.name) def wrapper(a, kw): return f(a, kw) return wrapper @deco2 def foo()…
- What is printed? python counter = 0 def countcalls(f): def wrapper(a, kw): global counter counter += 1 return f(a, kw) return wrapper…
- What is printed? python def applytwice(f): def wrapper(x): return f(f(x)) return wrapper @applytwice def inc(x): return x + 1 print(inc(5))
- What is printed? python def outerdeco(f): print("setup") def wrapper(a, kw): print("call") return f(a, kw) return wrapper @outerdeco def…
- What is printed? python def h(a, b, c): return a + b + c args = [1, 2, 3] print(h(args)) args2 = [1, 2] try: print(h(args2)) except…