Code Explanation
1. Importing asyncio
import asyncio
Imports Python’s built-in asyncio module.
asyncio is used for writing concurrent code using the async and await keywords.
2. Defining an Asynchronous Function
async def square(x):
await asyncio.sleep(0.1)
return x * x
Declares an async function square that takes an argument x.
await asyncio.sleep(0.1) simulates a delay of 0.1 seconds (like waiting for an API or I/O).
Returns the square of x.
Example:
square(2) will return 4 after 0.1s.
square(3) will return 9 after 0.1s.
3. Main Coroutine
async def main():
results = await asyncio.gather(square(2), square(3))
print(sum(results))
Defines another coroutine main.
asyncio.gather(square(2), square(3)):
Runs both coroutines concurrently.
Returns a list of results once both are done.
Here: [4, 9].
sum(results) → 4 + 9 = 13.
Prints 13.
4. Running the Event Loop
asyncio.run(main())
Starts the event loop and runs the main() coroutine until it finishes.
Without this, async code would not execute.
Final Output
13
.png)

0 Comments:
Post a Comment