🐍 Python for Everyone

← Back to the quiz

Chapter 26 Exercises (Categories 1-8) 35 min, hands-on

Exercises: Debugging Production Issues

How to run these Download starter.py below, then run python3 starter.py from inside the folder you saved it in. Every task uses only the standard library — no installs needed.

1 A safe dict lookup

Write safe_lookup(config, key, default) — return the value if present, otherwise default, never raising KeyError.

2 A safe top-N sum

Write safe_top_n(scores, n) — sum the first n items without ever indexing past the end of the list.

3 Catching the specific exception

Write safe_int_lookup(raw, key, default) — catch only KeyError, not a bare except:.

4 Validating input before arithmetic

Write safe_discount(price, percent_off) — convert percent_off to a float before using it.

5 Raising instead of implicitly returning None

Write find_user_or_raise(users, name) — raise a clear ValueError instead of implicitly returning None.

6 Handling a zero denominator

Write average_or_none(total, count) — return None instead of crashing when count is 0.

7 Handling a non-JSON response

Write parse_json_safe(raw_text) — catch json.JSONDecodeError specifically and return None.

🐞 Task 8 — Debug the Code

This is supposed to return 30 if the "timeout" key is missing, but its bare except: also hides a real typo in the config dict below ("timeoout", not "timeout"). Fix the except clause so it only catches KeyError.

buggy_load_timeout.py
def load_timeout(raw):
    try:
        return int(raw["timeout"])
    except:
        return 30


raw_config = {"timeoout": "45"}
print("load_timeout result:", load_timeout(raw_config))

9 Checking for a duplicate with a set

Write has_duplicate(items) — return True if any value appears more than once, using a set for the membership check.

10 Deduplicating while preserving order

Write dedupe_preserve_order(items) — remove duplicates, keeping only the first occurrence of each value.

11 Indexing records by key

Write index_by_key(records, key_name) — build a dict mapping each record's key value to the record itself.

12 Min and max without sorting

Write smallest_and_largest(numbers) — return (min(numbers), max(numbers)) without calling sorted().

13 Stopping at the first match

Write first_match_or_none(items, predicate) — return the first item where predicate(item) is True, stopping immediately once found.

🐞 Task 14 — Debug the Code

This is supposed to return items in reverse order, but it uses list.insert(0, x) in a loop, which is O(n) per call. Fix it to use .append() followed by one .reverse() call instead.

buggy_reversed_list.py
def reversed_list(items):
    result = []
    for item in items:
        result.insert(0, item)
    return result


print(reversed_list([1, 2, 3]))

15 Bounding a "recent" collection

Write bounded_recent_events(events, maxlen) — use collections.deque(maxlen=maxlen) so the result never holds more than maxlen items, no matter how large events is.

🐞 Task 16 — Debug the Code

SharedCounter uses a class-level count = [], which is shared by every instance instead of being per-instance. Fix it by creating self.count = [] inside __init__.

buggy_shared_counter.py
class SharedCounter:
    count = []

    def add(self, value):
        self.count.append(value)


a = SharedCounter()
b = SharedCounter()
a.add(1)
b.add(2)
print(a.count)

17 Deep copy for real independence

Write independent_copy(original) — use copy.deepcopy() so mutating a nested list/dict on the copy never affects the original.

18 Comparing floats safely

Write floats_equal(a, b) — use math.isclose(), never a plain ==, since floating-point arithmetic accumulates rounding error.

19 Rounding instead of truncating

Write round_quantity(value) — use round(), not int(), which silently truncates toward zero instead of rounding.

🐞 Task 20 — Debug the Code

get_page() treats a 1-based page_number as if it were already a 0-based offset, silently dropping the first page's records. Fix it to convert with (page_number - 1) * page_size.

buggy_get_page.py
def get_page(records, page_number, page_size):
    start = page_number * page_size
    return records[start:start + page_size]


records = list(range(10, 20))
print(get_page(records, 1, 3))

21 Never rely on dict key order

Write row_from_fixed_columns(record, column_order) — look up each value by column_order's order, never a dict's own key insertion order.

22 Missing environment variables, all at once

Write missing_env_keys(env, required_keys) — return a sorted list of every required key that's missing, the env-var version of Task 1's KeyError fix.

23 A safe retry with an idempotency key

Write charge_once(processed, idempotency_key, amount) — a retried call with the same key returns the original result instead of charging twice.

24 Avoiding the N+1 pattern

Write attach_names(records, lookup_table) — build the lookup once, up front, instead of scanning a second list per record.

25 Structured, not free-text, logging

Write build_log_record(order_id, amount, status) — return a dict with named fields, not a formatted string, so a log aggregator can query it directly.

🐞 Task 26 — Debug the Code

redact_password() builds a redacted copy but returns the original request dict by mistake, leaking the password. Fix it to return redacted instead.

buggy_redact_password.py
def redact_password(request):
    redacted = dict(request)
    redacted["password"] = "***"
    return request


print(redact_password({"user": "sam", "password": "hunter2"}))
← Back to Quiz Practice Bank →