Problem Statement
What are generator send and throw used for? Give a practical example.
Explanation
send pushes a value into a paused generator and resumes it until the next yield. throw injects an exception at the yield point. Together they allow two-way communication and controlled stop conditions.
This is useful for coroutines in older code or for advanced pipelines that adjust behavior on feedback, such as changing a step size in a stream processor.
Code Solution
SolutionRead Only
def coro():
total=0
while True:
x = yield total
if x is None: break
total += x
c = coro(); next(c)
print(c.send(3)); print(c.send(4)); c.throw(GeneratorExit)