Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.6 — asyncio: async and await
Python · Example 1 of 3

A coroutine is a recipe until it is awaited

Look at the order: the type prints first, and the body of greet runs only inside main.

asyncio runs many tasks on one thread. A function defined with async def is a coroutine that can pause at await, and the event loop (started by asyncio.run) runs whichever task is ready while the others wait.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a coroutine double(n) that sleeps 0.01 seconds and returns n * 2. Await it for 5 and print the result.

02

Start two tasks slow (sleeps 0.05, prints slow) and fast (sleeps 0.01, prints fast) and wait for both. What is printed?

03

This code prints nothing useful: async def get(): return 5 then inside main: value = get() and print(value + 1). Fix it.

Explain it without notes

01

What is the difference between a coroutine function and a coroutine object?

02

What does the event loop do, and what makes a task give up control?

03

Why does time.sleep inside a coroutine cause problems but asyncio.sleep does not?

04

What is the difference between await coro() and asyncio.create_task(coro())?

05

Does every await let other tasks run? What happens to the rest of the program if a coroutine awaits a million quick coroutines in a loop?

A coroutine is a recipe until it is awaited
Sign in to run this example in your browser.

Expected output

type: coroutine
nothing has printed yet
hello, Ada
hello, Linus
lengths: 3 5