Junior — Middle
Can you explain what courses are and how they work?
sobes.tech AI
Answer from AI
In Python, coroutines are special functions that allow pausing and resuming execution, which is useful for asynchronous programming and event handling.
Coroutines are based on the keywords async and await:
async defdeclares a coroutine.awaitis used to wait for the result of another coroutine or asynchronous operation.
Example of a simple coroutine:
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1) # simulate an asynchronous operation
print("World")
async def main():
await say_hello()
asyncio.run(main())
Here, say_hello is a coroutine that first prints "Hello", then pauses for 1 second without blocking the main thread, and then prints "World".
Coroutines allow writing asynchronous code that looks sequential, which simplifies reading and maintaining programs that work with network, input-output, and other operations requiring waiting.