Python Mastery – From Basics to Brilliance / Asynchronous Programming

async and await in Python

⚡ async and await

async and await are Python keywords used for asynchronous programming. They allow a program to handle other tasks while waiting for an operation to finish.


🔹 async

async is used to define an asynchronous function.

async def greet():
    print("Hello!")

Such a function is called a coroutine.


🔹 await

await is used inside an async function to wait for an asynchronous operation to complete.

import asyncio

async def greet():
    print("Hello")
    await asyncio.sleep(2)
    print("Done")

asyncio.run(greet())
Hello
Done

The await pauses this coroutine for 2 seconds, while allowing other asynchronous tasks to run.


🚀 Multiple Tasks

import asyncio

async def task(name):
    print(name, "started")
    await asyncio.sleep(2)
    print(name, "finished")

async def main():
    await asyncio.gather(
        task("Task 1"),
        task("Task 2")
    )

asyncio.run(main())

Both tasks can wait concurrently, rather than one completely finishing before the other starts.

async says "this function can run asynchronously."
await says "pause here until this async operation is ready, and let other tasks run meanwhile."