8. Coroutines

These snippets demonstrate the use of coroutines for multitasking and cooperative execution, including sending data, handling exceptions, and managing state. They also illustrate how coroutines can be

1. Basic Coroutine Example

Copy

def simple_coroutine():
    print("Coroutine started")
    x = yield
    print(f"Received: {x}")

coro = simple_coroutine()
next(coro)         # Start the coroutine
coro.send(42)      # Output: Coroutine started \n Received: 42

2. Coroutine with Multiple yield Statements

Copy

def multi_yield_coroutine():
    print("Coroutine started")
    x = yield "First yield"
    print(f"Received: {x}")
    y = yield "Second yield"
    print(f"Received: {y}")

coro = multi_yield_coroutine()
print(next(coro))  # Output: Coroutine started \n First yield
print(coro.send(10))  # Output: Received: 10 \n Second yield
coro.send(20)         # Output: Received: 20

3. Coroutine for Accumulating Values

Copy


4. Coroutine for Data Filtering

Copy


5. Coroutine for String Processing

Copy


6. Coroutine with Exception Handling

Copy


7. Coroutine with Closing Behavior

Copy


8. Coroutine for Logging Messages

Copy


9. Coroutine for Producing Fibonacci Numbers

Copy


10. Coroutine with Asynchronous Behavior Using asyncio

Copy

Last updated