Intermediate Python
3.1 Check whether a running total hits a target
Run this script and examine the two computed values. Are they exactly equal? Try printing each value with many decimal places.
def running_total(amounts):
"""Return the total by accumulating amounts one at a time."""
result = 0.0
for a in amounts:
result += a
return result
def direct_total(amounts):
"""Return the total by summing all amounts at once."""
return sum(amounts)
if __name__ == "__main__":
amounts = [0.1] * 10 # mathematically equals 1.0
t1 = running_total(amounts)
t2 = direct_total(amounts)
print(f"Running total: {t1!r}")
print(f"Direct total: {t2!r}")
if t1 == 1.0:
print("Running total is exactly 1.0")
else:
print(f"Running total is NOT exactly 1.0 (off by {abs(t1 - 1.0)!r})")
if t1 == t2:
print("Totals match.")
else:
print("Totals differ!")Show explanation
The bug is using == on floats computed by different routes, so the comparison returns False even when the values should be equal.
Shows: floating-point representation errors and how to use math.isclose.
To find it: print both values with 20 decimal places using f"{val:.20f}". You will see that one ends in ...000001 rather than matching the other exactly, revealing the rounding difference that makes == return False.
3.2 Scrape titles from a list of URLs
Run the scraper with the provided URL list, which includes one malformed URL. Does it process all the valid URLs? Check whether anything is silently discarded.
from urllib.parse import urlparse
URLS = [
"https://example.com/page1",
"https://example.com/page2",
"not-a-valid-url",
"https://example.com/page4",
"https://example.com/page5",
]
def fetch_title(url):
"""Return a simulated page title; raises ValueError for malformed URLs."""
parsed = urlparse(url)
if not parsed.scheme:
raise ValueError(f"Invalid URL: {url!r}")
return f"Title from {parsed.netloc}{parsed.path}"
def scrape_all(urls):
"""Fetch a title for each URL and return the list of results."""
titles = []
try:
for url in urls:
title = fetch_title(url)
titles.append(title)
except Exception:
pass
return titles
if __name__ == "__main__":
results = scrape_all(URLS)
valid = sum(1 for u in URLS if urlparse(u).scheme)
print(f"Got {len(results)} titles (expected {valid}):")
for t in results:
print(f" {t}")Show explanation
The bug is wrapping the fetch-and-parse loop in try/except Exception: pass to tolerate network timeouts. The ValueError raised by the URL parser is also caught and discarded, so the scraper silently stops processing after the first malformed URL.
Shows: how overly broad exception handlers swallow unrelated bugs, and how to use logging.exception to record errors instead of ignoring them.
To find it: replace pass in the except block with logging.exception("caught"). Run the script again and read the log output. You will see a ValueError from the URL parser printed for the malformed URL, proving the except block was swallowing the wrong exception type.
3.3 Find the top scorer in a CSV file
Run the script with the provided CSV file and read the traceback. Which line in the file triggers the error? Examine that line carefully.
import sys
def top_scorer(filename):
"""Return the (name, score) pair with the highest score."""
best_name = None
best_score = -1
with open(filename) as f:
next(f) # skip header
for line in f:
parts = line.strip().split(",")
name = parts[0]
score = int(parts[1])
if score > best_score:
best_score = score
best_name = name
return best_name, best_score
if __name__ == "__main__":
filename = sys.argv[1] if len(sys.argv) > 1 else "commas.csv"
name, score = top_scorer(filename)
print(f"Top scorer: {name} ({score})")name,score
Alice Johnson,95
Bob Smith,87
Martinez, Carlos,92
Wong, Jennifer,88
Diana Prince,79
Show explanation
The bug is that names containing a comma (e.g., “Smith, John”) cause line.split(',') to produce three fields instead of two, so the index used for the score points at the wrong element and the script crashes with an IndexError.
Shows: why hand-rolled CSV parsing fails on real data and when to use the csv module.
To find it: open the CSV in a text editor and find the row that triggers the IndexError. Count the commas on that line — there are two, not one. The extra comma sits inside a quoted name field that line.split(',') does not recognize as quoted.
3.4 Process a pipeline of records twice
Run the script and look at both outputs. Does each one produce the values you expected?
def positive_numbers(data):
"""Yield each positive number from data."""
return (x for x in data if x > 0)
if __name__ == "__main__":
data = [-1, 2, -3, 4, -5, 6, -7, 8]
gen = positive_numbers(data)
total = sum(gen)
count = sum(1 for _ in gen)
print(f"Total: {total}")
print(f"Count: {count}")
if count > 0:
print(f"Mean: {total / count}")
else:
print("Cannot compute mean: generator was exhausted before count was taken")Show explanation
The bug is that generators are exhausted after one pass, so the second use of the generator in the same expression produces no results.
Shows: that generators are single-use iterators and when to use lists instead.
To find it: print type(pipeline) to confirm it is a generator. Then assign results = list(pipeline) and print results a second time — the second access returns an empty list, proving the generator was exhausted on the first pass.
3.5 Cache results of an expensive calculation
Call the cached function twice with the same positional argument but a different keyword argument each time. Do both calls return the correct result?
def memoize(func):
"""Cache the results of func calls."""
cache = {}
def wrapper(*args, **kwargs):
key = args
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def power(base, exponent=2):
print(f" (computing {base}^{exponent})")
return base ** exponent
if __name__ == "__main__":
print(f"power(3) = {power(3)}")
print(f"power(3, exponent=3)= {power(3, exponent=3)}")
print(f"power(3, 3) = {power(3, 3)}")Show explanation
The bug is that the cache key does not include all function arguments (e.g., ignores keyword arguments), so the decorator returns the same result for different inputs.
Shows: how to construct correct cache keys and test with varied inputs.
To find it: call the cached function twice with the same positional argument but different keyword arguments — e.g., f(1, multiplier=2) then f(1, multiplier=3). If both return the same value, add print(key) inside the decorator to show the key is identical for both calls.
3.6 Write results to disk when processing fails
Run the script so that it raises an exception part-way through writing. Then open the output file. Does it contain complete data?
import os
import sys
def summarize(input_file, output_file):
"""Write uppercased non-blank lines from input_file to output_file."""
out = open(output_file, "w")
with open(input_file) as f:
for line in f:
line = line.rstrip("\n")
if not line:
raise ValueError(f"Unexpected blank line in {input_file!r}")
out.write(line.upper() + "\n")
out.close()
if __name__ == "__main__":
input_file = sys.argv[1] if len(sys.argv) > 1 else "unclosed.txt"
output_file = "unclosed_out.txt"
try:
summarize(input_file, output_file)
except ValueError as e:
print(f"Error: {e}")
if os.path.exists(output_file):
with open(output_file) as f:
lines = f.readlines()
print(f"Output has {len(lines)} line(s) — may be incomplete (buffer not flushed)")
for line in lines:
print(f" {line!r}")first line
second line
fourth line after blank
fifth line
Show explanation
The bug is using open() without a with statement. When an unhandled exception occurs midway through, the output file is left partially written because the write buffer is never flushed and close() is never called.
Shows: why context managers guarantee file cleanup even when exceptions occur, and how to use with open(…) as f to prevent data loss.
To find it: run the script so that it raises an exception midway through writing, then open the output file in a text editor. Count the records. If the count is less than expected, the buffer was never flushed — close() was never called because the exception skipped it.
3.7 Build a list of functions in a loop
Call each function in the list produced by make_multipliers(). Do they multiply by different numbers?
def make_multipliers():
"""Return a list of functions that multiply by 0, 1, 2, 3, 4."""
multipliers = []
for i in range(5):
multipliers.append(lambda x: x * i)
return multipliers
funcs = make_multipliers()
print([f(10) for f in funcs]) # expect [0, 10, 20, 30, 40], get [40, 40, 40, 40, 40]Show explanation
The bug is late binding. Each lambda captures the variable i, not the value it had when the lambda was created. By the time any lambda is called, the loop has finished and i is 4, so every lambda multiplies by 4.
Shows: that closures capture variables, not values, and why a loop that creates functions needs a way to freeze the current value (e.g. a default argument lambda x, i=i: x * i).
To find it: print what each function returns — they all return the same value. Capture the value with lambda x, i=i: x * i.
3.8 Update a variable in an enclosing function
Call the counter returned by make_counter(). Does it return 1?
def make_counter():
count = 0
def increment():
count = count + 1
return count
return increment
counter = make_counter()
print(counter()) # expect 1, get UnboundLocalErrorShow explanation
The bug is assigning to count without declaring it nonlocal. Any assignment to a name inside a function makes that name local, so count = count + 1 tries to read a local count before it exists and raises UnboundLocalError.
Shows: Python’s scoping rules (LEGB) and that nonlocal (or global) is required to assign to a variable from an enclosing scope.
To find it: the traceback says UnboundLocalError: local variable 'count' referenced before assignment. Add nonlocal count as the first line of increment.
3.9 Preserve a function’s name and docstring
Inspect add.__name__ and add.__doc__ after decorating it. Do they match the original function?
def logged(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logged
def add(a, b):
"""Return a + b."""
return a + b
print(add(2, 3)) # calling add / 5
print(add.__name__) # expect 'add', get 'wrapper'
print(add.__doc__) # expect 'Return a + b.', get NoneShow explanation
The bug is the missing @functools.wraps(func) on the wrapper. Without it, the decorator returns a function named wrapper with no docstring, so help(), repr(), and introspection tools report the wrong metadata.
Shows: how decorators replace the original function object, and why functools.wraps is needed to copy __name__, __doc__, and other attributes to the wrapper.
To find it: print add.__name__ — it shows wrapper, not add. Add @functools.wraps(func) above the wrapper function.
3.10 Pair up two lists of different lengths
Pair a list of three names with a list of two scores. Does every name get a score?
def pair(names, scores):
return list(zip(names, scores))
names = ["Alice", "Bob", "Carol"]
scores = [90, 85]
print(pair(names, scores)) # expect 3 pairs, get [('Alice', 90), ('Bob', 85)]Show explanation
The bug is that zip stops at the shorter iterable. When the two lists have different lengths, zip silently drops the extra items from the longer one, so the last name is missing from the result.
Shows: that zip truncates to the shortest input, and when mismatched lengths matter use itertools.zip_longest (with a fill value) instead.
To find it: compare len(names) and len(scores) to the number of pairs returned. The count is 2, not 3. Use itertools.zip_longest(names, scores) to keep all names.