Skip to content
pythonadvanced

Python Asynchronous Programming

asyncio, coroutines, tasks

6 questions

By EZ4Code Team

1. What is the keyword to define a coroutine function?

async def foo():
    pass
async def
def async
coroutine def
await def
Explanation: Use async def to define a coroutine function; calling it returns a coroutine object that needs to be executed in an event loop.

2. What does the await keyword do?

Pauses the coroutine until the awaitable completes, yielding the event loop meanwhile
Starts a new thread
Blocks the entire program
Declares a variable
Explanation: await is used to wait for an awaitable (coroutine/Task/Future), suspending the current coroutine and returning control to the event loop to avoid blocking.

3. Which function is used to concurrently schedule multiple coroutines?

await asyncio.gather(coro1, coro2)
asyncio.gather()
asyncio.run()
asyncio.sleep()
asyncio.wait_for()
Explanation: asyncio.gather(*aws) concurrently schedules multiple awaitables and returns a list of results in order; run() is used to run top-level coroutines.

4. What does asyncio.create_task() do?

Wraps a coroutine as a Task and immediately schedules it for execution
Cancels a coroutine
Creates a new process
Waits for a coroutine to complete
Explanation: create_task(coro) wraps a coroutine into a Task object and schedules it for concurrent execution in the event loop; the returned Task can be awaited or cancelled.

5. What is the output order of the following code? async def main(): print('A') await asyncio.sleep(0) print('B') asyncio.run(main())

async def main():
    print('A')
    await asyncio.sleep(0)
    print('B')

asyncio.run(main())
A then B
B then A
Only outputs A
Error
Explanation: The coroutine executes sequentially; await asyncio.sleep(0) only yields the event loop once, then continues to print B.

6. Regarding the relationship between asyncio and multithreading, which is correct?

asyncio is single-threaded concurrency based on an event loop; multithreading is true parallelism
asyncio is just multithreading
asyncio cannot be used for IO-intensive tasks
Multithreading is always faster than asyncio
Explanation: asyncio achieves concurrency within a single thread via an event loop, suitable for IO-intensive tasks; multithreading is scheduled by the OS, suitable for blocking tasks or parallelism.

More python Quizzes