Code Explanation:
1. Importing the asyncio Module
import asyncio
asyncio is a Python library that allows writing asynchronous code.
It helps run tasks concurrently (not in parallel, but without blocking).
2. Defining an Asynchronous Function
async def double(x):
await asyncio.sleep(0.05)
return x * 2
async def declares an asynchronous function.
await asyncio.sleep(0.05) → simulates a small delay (0.05 seconds) to mimic some async task like network I/O.
After waiting, the function returns x * 2.
Example: double(3) → waits, then returns 6.
3. Defining the Main Coroutine
async def main():
results = await asyncio.gather(double(3), double(4), double(5))
print(max(results), sum(results))
a) async def main():
Another coroutine that coordinates everything.
b) await asyncio.gather(...)
Runs multiple async tasks concurrently:
double(3) → returns 6 after delay.
double(4) → returns 8 after delay.
double(5) → returns 10 after delay.
asyncio.gather collects results into a list:
results = [6, 8, 10].
c) print(max(results), sum(results))
max(results) → largest number → 10.
sum(results) → 6 + 8 + 10 = 24.
Prints:
10 24
4. Running the Async Program
asyncio.run(main())
This starts the event loop.
Runs the coroutine main().
The program executes until main is finished.
Final Output
10 24
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment