Sobes.tech
Middle

Explain the output of the following Python asyncio code and why it behaves that way: ```python import asyncio async def say_hello(): print(1) await asyncio.sleep(1) print(2) async def main(): await say_hello() task = asyncio.create_task(say_hello()) print(3) await task asyncio.run(main()) ```

sobes.tech AI

Answer from AI

The program output will be:

1
2
1
3
2

Explanation:

  1. In main(), await say_hello() is called first. This starts say_hello(), which prints 1, then does await asyncio.sleep(1) — suspending the coroutine for 1 second, allowing other tasks to run.
  2. After the pause, say_hello() continues and prints 2. This call completes fully.
  3. Then, a task task = asyncio.create_task(say_hello()) is created, which runs say_hello() asynchronously but does not wait for it to finish.
  4. Immediately after creating the task, 3 is printed.
  5. Then, await task waits for the task to complete, which first prints 1, then waits 1 second, and after that prints 2.

Thus, the first call to say_hello() executes sequentially, while the second is launched in parallel with the output of 3, which is reflected in the output order.