ProgrammingVery hardProduct company OA
What is printed?
What is printed?
def acc():
total = 0
while True:
try:
x = yield total
except ValueError:
total = 0
continue
if x is None:
break
total += x
yield "done"
g = acc()
print([next(g), g.send(5), g.send(7), g.throw(ValueError), g.send(2), g.send(None)])- A. [0, 5, 12, 12, 14, 'done']
- B. [0, 5, 12, 0, 2, 'done']
- C. [0, 5, 12, 0, 2, None]
- D. [None, 5, 12, 0, 2, 'done']
Correct answer: B. [0, 5, 12, 0, 2, 'done']
next(g) runs to the first yield and gives 0. send(5) resumes with x = 5, total 5, yields 5; send(7) yields 12. throw(ValueError) raises inside the paused yield, the except resets total to 0 and continue reaches the yield again, so throw itself returns 0. send(2) yields 2. send(None) breaks the loop and the generator yields "done" — throw and send both return the NEXT yielded value.
More Python Programming questions
- What is printed? python class Base: def init(self): self.log = ["Base"] class L(Base): def init(self): super().init() self.log.append("L")…
- What is printed? python class D: def get(self, obj, typ): return "desc" class DD(D): def set(self, obj, v): pass class C: a = D() b = DD()…
- What is printed? python class K: def init(self, v): self.v = v def hash(self): return hash(self.v) def eq(self, o): return self.v == o.v k…
- What is printed? python def f(x): try: r = 10 / x except ZeroDivisionError: r = "inf" return r else: r = round(r) finally: r = str(r) +…
- What is printed? python class A: def eq(self, o): print("A", end=" ") return NotImplemented class B: def eq(self, o): print("B", end=" ")…
- What is printed? python class N: def add(self, o): return "N.add" def radd(self, o): return "N.radd" class S(N): def radd(self, o): return…