Async & Await
Asynchronous programming allows Python to handle multiple tasks efficiently without blocking execution.
Synchronous Code
import time
def task():
time.sleep(2)
print("Task done")
task()
Asynchronous Code
import asyncio
async def task():
await asyncio.sleep(2)
print("Task done")
asyncio.run(task())
Running Multiple Tasks
async def main():
await asyncio.gather(task(), task())
asyncio.run(main())
When to Use Async?
- Web scraping
- API calls
- Web servers
📝 Practice: Run 3 async tasks with different delays.