Skip to content
Chapter Practice Arena

Data, APIs, and Concurrency Problems

Targeted practice challenges specifically curated for this chapter. Inspect hints, verify outputs, and check Pythonic solutions.

All Chapters
Difficulty:
Chapter:
Showing 6 challenges · 20 total · Page 1 of 4
Create an async function double(value) that awaits asyncio.sleep(0) and returns value * 2. Use asyncio.gather() to call it with 3 and 5, then print the results.
Starter Code
import asyncio

async def double(value):
    # Yield asynchronously and return value * 2.
    pass

async def main():
    # Gather both results and print the returned list.
    pass

asyncio.run(main())
Expected Output:[6, 10]
Write a coroutine that raises ValueError('Bad data'). In main(), await it inside a try/except block and print the exception message prefixed with Error:.
Starter Code
import asyncio

async def read_data():
    # Raise ValueError('Bad data').
    pass

async def main():
    # Await read_data() and catch ValueError.
    pass

asyncio.run(main())
Expected Output:Error: Bad data
A program must wait for responses from several independent network services. Explain why threads may help, and name one alternative concurrency approach.
Starter Code
# Write a short explanation in your own words.
Expected Output:A written explanation identifying I/O-bound waiting and a suitable alternative such as asyncio.
#4intermediateThreading and Shared State
Create two threads. Each thread must increment the same counter 1,000 times. Use a lock to protect each increment and print the final counter after both threads finish.
Starter Code
import threading

counter = 0
lock = threading.Lock()

# Define the worker and start two threads.
Expected Output:2000
#5intermediateThreading and Shared State
Create a threading.Event. One thread should print Ready and set the event. Another thread should wait for the event and then print Starting. Ensure the output always places Ready before Starting.
Starter Code
import threading

ready = threading.Event()

# Define the initializer and consumer functions.
# Start both threads and join both.
Expected Output:Ready Starting
#6beginnerHTTP Requests and APIs
Use urlencode() to encode the dictionary {'page': 2, 'sort': 'name'} and print the result.
Starter Code
from urllib.parse import urlencode

# Build and print the query string.
Expected Output:page=2&sort=name