Async Programming Quiz - Languages Python
Free practice quiz: Async Programming (Languages Python). 52 multiple-choice questions with answers and explanations. Play online, no sign-up needed.
Play all 52 questions freeSample questions
Which keyword is used to define a coroutine in Python?
- async def
- def async
- await def
- def await
Show answer
Answer: A. async def
The `async def` syntax is used to define a coroutine function in Python, which can be paused and resumed.
What is a 'Task' in asyncio?
- A wrapper around a coroutine that allows it to be scheduled.
- A separate thread for running coroutines.
- A mechanism for synchronous execution.
- A data structure for storing results.
Show answer
Answer: A. A wrapper around a coroutine that allows it to be scheduled.
A Task is a subclass of Future, representing the result of executing a coroutine. It's how asyncio schedules coroutines to run concurrently.
What is the `asyncio` module primarily designed for?
- Writing concurrent code using the async/await syntax.
- High-performance numerical computation.
- Web scraping with multiple threads.
- Database management.
Show answer
Answer: A. Writing concurrent code using the async/await syntax.
The `asyncio` module in Python is the standard library for writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, running network clients and servers, and other related primitives.
Which method can be used to get the result of a completed Task without blocking the event loop?
- `task.result()` (if the task is done)
- `await task`
- `asyncio.get_result(task)`
- `task.get()`
Show answer
Answer: A. `task.result()` (if the task is done)
If a Task is already done, `task.result()` will return its result immediately without blocking. If the task is not done, calling `task.result()` will raise an `InvalidStateError`. `await task` is the non-blocking way to wait for a task.
What is the purpose of `asyncio.gather(*coros, loop=None, return_exceptions=False)`?
- To run multiple coroutines concurrently and return their results in a list.
- To run coroutines sequentially.
- To return the first result and cancel others.
- To schedule coroutines without returning results.
Show answer
Answer: A. To run multiple coroutines concurrently and return their results in a list.
`asyncio.gather` is designed to run multiple awaitables concurrently. It collects their results in the order they were passed and returns them as a list once all have completed.