ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
a = 5
def outer():
x = 10
def inner():
nonlocal x
x += a
return x
return inner()
print(outer())- A. 10
- B. 5
- C. 15
- D. UnboundLocalError
Correct answer: C. 15
nonlocal x binds to outer's local x (10). a is just read from the global scope (no nonlocal/global needed for reading). x += a makes x = 10 + 5 = 15, which inner returns and outer passes along.
More Python Programming questions
- What is printed? python class Temperature: def init(self, celsius=0): self.celsius = celsius @property def fahrenheit(self): return…
- What is printed? python def f(a, b, , c=10, kwargs): return a + b + c + sum(kwargs.values()) print(f(1, 2, d=3, e=4)) print(f(1, 2, c=100))
- What is printed? python class Animal: sound = "..." def makesound(self): return f"{type(self).name} says {self.sound}" class Dog(Animal)…
- What is printed? python def outer(): x = [] def appendVal(v): x.append(v) return x return appendVal f1 = outer() f2 = outer() print(f1(1)…
- What is printed? python def validate(f): def wrapper(x): if x < 0: raise ValueError("negative") return f(x) return wrapper @validate def…
- What is printed? python def makeFuncs(): return [lambda x, n=n: x n for n in range(1, 4)] fns = makeFuncs() print([f(2) for f in fns])