ProgrammingVery hardPython · GATE DA · Advanced
What is printed?
What is printed?
def make():
n = 0
def inc():
n += 1
return n
return inc
try:
print(make()())
except Exception as e:
print(type(e).__name__)
def make2():
n = [0]
def inc():
n[0] += 1
return n[0]
return inc
c = make2(); c(); print(c(), make2()())- A. UnboundLocalError / 2 1
- B. UnboundLocalError / 2 2
- C. UnboundLocalError / 1 1
- D. NameError / 2 1
Correct answer: A. UnboundLocalError / 2 1
n += 1 makes n local to inc, so reading it first raises UnboundLocalError (a NameError subclass, but the exact type name printed is UnboundLocalError). The list version mutates a closed-over object; each make2() has its own list.
More Python Programming questions
- What is printed? python import copy a = [1, 2] b = [a, a] c = copy.deepcopy(b) d = copy.copy(b) c[0].append(3) print(b, c[0] is c[1], d[0]…
- What is printed? python class M: def enter(self): print('in', end=' '); return self def exit(self, t, v, tb): print('exit', t.name if t…
- What is printed? python a = [0] 3 m = [a] 2 m[0][1] = 5 n = [[0] 3 for in range(2)] n[0][1] = 5 print(m, n, a)
- What is printed? python try: try: 1 / 0 except ZeroDivisionError as e: raise ValueError('bad') from None except ValueError as v…
- What is printed? python def deco(tag): def w(f): def g(a): return f'<{tag}>' + f(a) + f'</{tag}>' return g return w @deco('b') @deco('i')…
- What is printed? python g = (x 2 for x in range(3)) lst = [1, 2, 3] h = (y for y in lst if y > n) n = 1 lst = [5] print(list(g), list(h))