Coroutines & asyncio.run — Series 3

Preview — 3 of 10 questions

What is the output of the following code?

javascript
import asyncio

async def greet():
    print("body ran")
    return "hi"

async def main():
    coro = greet()
    print(type(coro))
    result = await coro
    print(result)

asyncio.run(main())
A<class 'coroutine'>, body ran, hi
Bbody ran, <class 'coroutine'>, hi
Chi, <class 'coroutine'>, body ran
D<class 'coroutine'>, hi, body ran

What is the output of the following code?

javascript
import asyncio

async def main():
    result = await asyncio.sleep(0.01)
    print(result)
    print(result is None)

asyncio.run(main())
ANone, False
BNone, True
C0.01, False
D<class 'NoneType'>, True

What is the output of the following code?

javascript
import asyncio
import time

async def work():
    await asyncio.sleep(0.1)

async def main():
    start = time.perf_counter()
    await work()
    await work()
    sequential_time = time.perf_counter() - start

    start2 = time.perf_counter()
    await asyncio.gather(work(), work())
    concurrent_time = time.perf_counter() - start2

    print(sequential_time > concurrent_time)
    print(concurrent_time < 0.15)

asyncio.run(main())
ATrue, False
BFalse, True
CTrue, True
DFalse, False

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.