ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
adders = []
for i in range(3):
def adder(x, i=i):
return x + i
adders.append(adder)
print(adders[0](10), adders[2](10))- A. 13 13
- B. 10 12
- C. 10 10
- D. 13 11
Correct answer: B. 10 12
Default argument i=i captures the current loop value of i at the time each function is DEFINED. adders[0] captured i=0 (10+0=10) and adders[2] captured i=2 (10+2=12).
More Python Programming questions
- What is printed? python x = 1 def outer2(): x = 2 def inner(): print(x) x = 3 return inner outer2()()
- 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…