python · level 3 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Making tea, one step at a time. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import asyncio
async def boil():
print("kettle on")
await asyncio.sleep(0.1)
print("kettle boiled")
return "hot water"
async def main():
print("start")
water = await boil()
print("making tea with", water)
asyncio.run(main())
your turn
Your turn. Await a pretend weather reply.
Fill the first blank so main waits for the reply. In the second, give asyncio.run the coroutine to start. Change the temperature in the reply if you like.
fix it
The score is a strange object, not 42. Fix it!
- The output shows a coroutine object, not a number. Did
get_scoreever run? - Calling a coroutine only builds it. Something must wait for it to finish.
- Put
awaitbeforeget_score()on line 8, then run.
nailed it
you made your first coroutines. :D
async defmakes a coroutine that can pause.awaitwaits for a result without freezing everything.asyncio.run(main())starts the event loop, once, at the bottom.
new words in your collection
- coroutine
- await
- event loop
This lesson isn’t saved. A free account remembers every lesson you finish.