ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
def f():
x = 1
def g():
return x
x = 2
return g
def h():
for x in [1, 2]:
pass
return lambda: x
print(f()(), h()())- A. 1 2
- B. 1 1
- C. 2 2
- D. 2 1
Correct answer: C. 2 2
Closures capture variables, not values: g reads x as it is when called (2). The lambda in h reads x after the loop finished, also 2.
More Python Programming questions
- What is printed? python class Node: def init(self, v, nxt=None): self.v, self.nxt = v, nxt def iter(self): n = self while n: yield n.v n =…
- What is printed? python import heapq h = [5, 1, 4] heapq.heapify(h) heapq.heappush(h, 0) small = heapq.heappop(h) print(small, h[0]…
- What is printed? python from collections import deque d = deque([1, 2, 3], maxlen=3) d.append(4) d.appendleft(0) d.rotate(1)…
- What is printed? python from collections import namedtuple P = namedtuple("P", "x y", defaults=[0]) p = P(1) q = p.replace(y=5) print(p…
- What is printed? python from dataclasses import dataclass, field @dataclass class Item: name: str tags: list = field(defaultfactory=list)…
- What is printed? python from dataclasses import dataclass @dataclass(frozen=True) class Pt: x: int y: int = 0 p = Pt(1) try: p.x = 5…