×

python · level 3 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is a function that can pause while it waits.

Programs spend a lot of time waiting: for a website, a database, a file. Write async def and you get a coroutine, a function that can pause during the wait instead of freezing everything.

Inside a coroutine, pauses until another coroutine finishes, then hands you its result. Here, await asyncio.sleep(0.1) stands in for a slow reply, because these lessons run without the internet.

Coroutines need an to run them. asyncio.run(main()) starts one, runs main to the end, then stops. Write it once, on its own line, at the bottom of your program.

import asyncio
import json

async def fetch_user(user_id):
    await asyncio.sleep(0.1)
    reply = '{"id": 7, "name": "Ana"}'
    return json.loads(reply)

async def main():
    user = await fetch_user(7)
    print("Hello,", user["name"])

asyncio.run(main())

The JSON replies in these lessons are pretend: they are strings written straight into the code.