All quizzesMedium
Tasks & Concurrency — Series 3
Preview — 3 of 10 questions
What is the output of the following code?
javascript
import asyncio
async def main():
q = asyncio.Queue(maxsize=2)
q.put_nowait(1)
q.put_nowait(2)
try:
q.put_nowait(3)
except asyncio.QueueFull:
print("QueueFull")
print(q.get_nowait())
print(q.get_nowait())
try:
q.get_nowait()
except asyncio.QueueEmpty:
print("QueueEmpty")
asyncio.run(main())AQueueFull, 1, 2, QueueEmpty
B1, 2, 3, QueueEmpty
CQueueFull, 1, 2, 3
DQueueFull, 2, 1, QueueEmpty
What is the output of the following code?
javascript
import asyncio
async def fail():
raise ValueError("bad")
async def main():
task = asyncio.create_task(fail())
await asyncio.sleep(0.01)
print(task.done())
try:
task.result()
except ValueError as e:
print("ValueError:", e)
asyncio.run(main())ATrue, ValueError: bad, then the program crashes anyway once main() returns
BTrue, ValueError: bad
CFalse, ValueError: bad
DTrue, None
What is the output of the following code?
javascript
import asyncio
async def worker(n, delay):
await asyncio.sleep(delay)
return n
async def main():
t1 = asyncio.create_task(worker(1, 0.05))
t2 = asyncio.create_task(worker(2, 0.3))
done, pending = await asyncio.wait([t1, t2], timeout=0.1)
print(len(done), len(pending))
print(t1 in done)
print(t2 in pending)
t2.cancel()
asyncio.run(main())A0 2, False, True
B1 1, False, False
C1 1, True, True
D2 0, True, False
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.