Code Explanation:
1. Importing the asyncio module
import asyncio
The asyncio library is used for asynchronous programming in Python.
It allows us to run multiple tasks concurrently without creating multiple threads.
2. Defining an async function
async def f(x):
return x * 2
async def defines an asynchronous function (coroutine).
f(x) takes an argument x and returns x * 2.
Since there’s no await inside, it just wraps a normal computation in an async function.
3. Defining the main coroutine
async def main():
res = await asyncio.gather(f(2), f(3), f(4))
print(res)
main() is another async function.
Inside it, we use:
asyncio.gather() → runs multiple coroutines concurrently.
Here, it runs f(2), f(3), and f(4) at the same time.
Each call will return 2 * 2 = 4, 3 * 2 = 6, and 4 * 2 = 8.
The result is collected in a list: [4, 6, 8].
print(res) outputs the result.
4. Running the main coroutine
asyncio.run(main())
This is the entry point for running async code.
asyncio.run() starts the event loop and runs the main() coroutine until it finishes.
Final Output:
[4, 6, 8]
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment