Code Explanation:
1. Importing the Module
import asyncio
Imports Python’s built-in asyncio library.
It is used for writing asynchronous code (code that runs concurrently without blocking execution).
2. Defining an Asynchronous Function
async def double(x):
await asyncio.sleep(0.05)
return x * 2
async def double(x): → Defines an asynchronous function named double.
await asyncio.sleep(0.05) → Pauses execution for 0.05 seconds without blocking other tasks.
return x * 2 → After waiting, it returns the doubled value of x.
3. Defining the Main Asynchronous Function
async def main():
results = await asyncio.gather(double(2), double(3), double(4))
print(sum(results))
async def main(): → Another asynchronous function called main.
await asyncio.gather(...):
Runs multiple async tasks concurrently (double(2), double(3), double(4)).
Collects their results into a list: [4, 6, 8].
print(sum(results)):
Calculates the sum of [4, 6, 8] → 18.
4. Running the Asynchronous Program
asyncio.run(main())
Starts the event loop.
Executes main() until completion.
Ensures all asynchronous tasks inside are executed.
Final Output
18
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment