0Pricing
Python Academy · Lesson

Coroutines and the event loop

Define coroutines with async def and run them with asyncio.run().

What Is Concurrency?

Asyncio provides cooperative concurrency: a single thread handles many tasks by switching between them whenever one is waiting for I/O.

# Traditional: blocking I/O holds the whole thread
# Asyncio: while waiting for I/O, run other coroutines

import asyncio

async def main():
    print("Hello")
    await asyncio.sleep(1)   # yield control
    print("World")

asyncio.run(main())

async def — Coroutine Functions

Functions defined with async def are coroutine functions. Calling them returns a coroutine object; they only execute when awaited or scheduled.

import asyncio

async def greet(name):
    return f"Hello, {name}"

result = asyncio.run(greet("Alice"))
print(result)   # Hello, Alice

All lessons in this course

  1. Coroutines and the event loop
  2. await, Tasks, and Gathering
  3. Async Context Managers and Iterators
  4. Async I/O Patterns in Production
← Back to Python Academy