ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
x = 1
def f():
return x
def g():
x = 2
return f()
def h():
global x
x = 3
return f()
print(g(), h(), f())- A. 1 3 3
- B. 2 3 3
- C. 1 3 1
- D. 2 2 3
Correct answer: A. 1 3 3
f always reads the module-level x (lexical scoping), not the caller's local. g's local x = 2 is invisible to f; h rebinds the global to 3, which f then sees.
More Python Programming questions
- What is printed? python class Celsius: def init(self, t=0): self.t = t def get(self, obj, owner): return self if obj is None else obj.c…
- What is printed? python class Vec: def init(self, c): self.c = c def mul(self, k): return Vec((x k for x in self.c)) rmul = mul def…
- What is printed? python class Ordered: def init(self, v): self.v = v def lt(self, o): print("lt", end=" ") return self.v < o.v def…
- What is printed? python import functools @functools.totalordering class V: def init(self, n): self.n = n def eq(self, o): return self.n ==…
- What is printed? python def f(): l = [] for i in range(3): try: if i == 0: raise ValueError l.append(i) except ValueError: l.append("v")…
- What is printed? python def risky(n): if n == 1: raise KeyError(n) if n == 2: raise IndexError(n) return n res = [] for n in range(4)…