Explain it simply
Explain it simply
If Exercise Set 1 was practising single notes, Set 2 is playing chords. These tasks combine concepts from the Intermediate chapters: classes, error handling, file handling and comprehensions.
Real projects rarely let you work with one concept at a time. A bank app uses an account class, an exception for when money runs short, and a file to keep statements, all at once. Solving these tasks yourself and running the code will sharpen your debugging skills as well.
Problem → Why → Solution
The problem: code that only works on the happy path
The draft below works when you run it with ordinary values. But try withdraw(-50): -50 is not greater than the balance, so the check passes and balance -= -50 raises the balance to 150. A "withdrawal" just added money.
When money is short, the class prints a message and returns, so the calling code has no way to know whether the withdrawal happened. In the file part, a missing notes.txt stops the program, and if reading fails midway, the file is never closed.
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
print("Not enough balance!") # the caller cannot tell it failed
return
self.balance -= amount # withdraw(-50) adds 50
acc = BankAccount(100)
acc.withdraw(-50)
f = open("notes.txt") # crashes if missing, never closed
print(f.read())Why does this happen?
The draft never asked what could go wrong. The class does not guard its own state, it reports errors with print instead of an exception, and it leaves file cleanup to luck. A single happy-path run never exercises any of these three failure paths.
Core concept: plan state, failures and cleanup
Before starting an intermediate task, ask three questions. Who owns the state? What can fail? What must always happen, whatever goes wrong (cleanup)? The three tasks in this lesson each answer one of them.
1. A class guards its own state
Only deposit() and withdraw() change the balance, so the checks live in those methods. A zero or negative amount raises ValueError, which means no code anywhere can push the balance into an invalid state.
2. Raise, do not print
Subclass Exception to create InsufficientFundsError. It carries the balance and amount as attributes, so the caller decides how to react: a command-line app prints a message, a web app returns a 4xx response. The class never needs to know which interface is calling it.
3. try / except / else / finally
Name only the exceptions you expect in except. finally runs every time, even when there is an exception or a return, which is why the example's second read prints "Read attempt finished" before the caller prints "First line". For cleanup such as closing a file, a with statement is clearer: it closes the file however the block is left.
4. Open files explicitly
Always pass encoding="utf-8". The default encoding depends on the Python version and platform, so a file with Myanmar text can open on one computer and raise UnicodeDecodeError on another. FileNotFoundError is a subclass of OSError. In tests, tempfile.TemporaryDirectory() keeps you away from real files and cleans up at the end.
5. Comprehensions and sorting
{w: len(w) for w in words} builds the dictionary in one expression. sorted(..., key=lambda item: item[1]) orders by length, and because sorted() is stable, words of equal length keep their original order.
| Block | When it runs |
|---|---|
| try | First, always |
| except X | Only if X (or a subclass) was raised in try |
| else | Only if try raised nothing |
| finally | Always, even after a return or an uncaught exception |
- Decide who owns each piece of state
- List everything that can fail
- Raise a specific exception
- Clean up with with or finally
- Test the failure paths too
The happy path is only half of the code; the other half is what happens when things go wrong.
General pattern
class DomainError(Exception):
pass
try:
result = risky_operation()
except DomainError as err:
handle(err)
else:
use(result)
finally:
clean_up()Define your own exception class, catch only the error you expect, put the success code in else, and put the cleanup in finally.
The three tasks, solved deterministically
Reading notes.txt from the current folder would make the result depend on where you run the script, so the code tries both cases, file missing and file present, inside a temporary folder, and the output is always the same. BankAccount also rejects negative amounts, and InsufficientFundsError carries the balance and the amount.
import os
import tempfile
# Task 1: BankAccount with a custom exception
class InsufficientFundsError(Exception):
def __init__(self, balance, amount):
super().__init__(f"cannot withdraw {amount}, balance is {balance}")
self.balance = balance
self.amount = amount
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError(f"amount must be positive, got {amount}")
self.balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError(f"amount must be positive, got {amount}")
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
acc = BankAccount(1000)
acc.deposit(500)
try:
acc.withdraw(2000)
except InsufficientFundsError as e:
print(f"Error: {e}")
finally:
print(f"Current balance: {acc.balance}")
try:
acc.deposit(-50)
except ValueError as e:
print(f"Error: {e}")
# Task 2: safe file read - try/except/finally around open()
def read_first_line(path):
try:
with open(path, encoding="utf-8") as f:
return f.readline().strip()
except FileNotFoundError:
print(f"File not found: {os.path.basename(path)} - please check the name.")
return None
finally:
print("Read attempt finished")
with tempfile.TemporaryDirectory() as folder:
notes = os.path.join(folder, "notes.txt")
read_first_line(notes) # file does not exist yet
with open(notes, "w", encoding="utf-8") as f:
f.write("Buy milk\nCall Ko Ko\n")
print("First line:", read_first_line(notes))
# Task 3: dict comprehension, then sort by length
words = ["python", "is", "fun", "and", "powerful"]
word_lengths = {w: len(w) for w in words}
by_length = dict(sorted(word_lengths.items(), key=lambda item: item[1]))
print(by_length)Code breakdown
- An exception that carries data
super().__init__(f"cannot withdraw {amount}, balance is {balance}")super().__init__() sets the message that str(e) shows, while self.balance and self.amount keep the values for code that needs them.
- Guard the state
if amount <= 0:Both methods start with this check, so deposit(-50) raises ValueError and the balance stays at 1500.
- finally always reports
print(f"Current balance: {acc.balance}")This line sits in finally, so the balance is shown whether withdraw() succeeded or failed.
- with plus encoding
with open(path, encoding="utf-8") as f:with closes the file even if readline() fails, and the explicit encoding makes the read behave the same on every platform.
- finally runs before the caller
return f.readline().strip()finally runs before the return value reaches the caller, which is why "Read attempt finished" appears above "First line: Buy milk" in the output.
- A stable sort by length
by_length = dict(sorted(word_lengths.items(), key=lambda item: item[1]))fun and and both have length 3, but sorted() is stable, so fun, which came first in the list, stays first.
Error: cannot withdraw 2000, balance is 1500
Current balance: 1500
Error: amount must be positive, got -50
File not found: notes.txt - please check the name.
Read attempt finished
Read attempt finished
First line: Buy milk
{'is': 2, 'fun': 3, 'and': 3, 'python': 6, 'powerful': 8}else and finally side by side
The else block is used less often, but it earns its place. Keep only the line that may fail inside try and move the code that should run on success into else, so except cannot accidentally catch an unrelated error. Run the function below and note when each line appears.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("cannot divide by zero")
return None
else:
print("division ok")
return result
finally:
print("finally runs either way")
print(divide(10, 4))
print(divide(1, 0))In real projects
In real projects
Payment systems raise domain exceptions such as InsufficientFundsError in the service layer, and the API layer turns them into 4xx responses. They store money as Decimal or integer cents rather than float, because 0.1 + 0.2 gives 0.30000000000000004. CSV import jobs do not reject a whole file over one bad line; they record the line number and report it, which is exactly the pattern the challenge's Inventory class follows.
Teams test file code with temporary folders, such as pytest's tmp_path fixture. For each challenge, prepare a short design note, success and failure tests, and evidence that cleanup happened; code reviewers ask about all three. Only once the code is correct and readable is it worth making it faster, because early optimisation tends to hide bugs.
Common mistakes
Common mistakes
Swallowing errors with except: pass
A bare except or except Exception: pass silently hides not just FileNotFoundError but also the NameError from a typo. The program keeps running and nobody knows why the data is missing.
Printing errors inside the class
If withdraw() prints and returns, the caller cannot tell whether it worked, and in a web app the message lands in a server log instead of reaching the user. Raise, and let the caller decide how to show it.
Not rejecting negative amounts
With only the amount > self.balance check, withdraw(-50) deposits money. For every method that takes a number, think about zero and negatives.
Opening files without with or an encoding
With f = open(...), an error leaves the file open, and without an encoding, code that works on one platform can raise UnicodeDecodeError on another.
Best practices
Best practices
- End exception class names with Error and say what went wrong, as in InsufficientFundsError
- Keep each try block as short as possible, holding only the line that can fail
- Put the values needed to fix the problem (amount, balance, line number) in the message
- Write one success test and at least one failure test for every task
Mini challenge
An Inventory class that loads from a file
Write an Inventory class that loads stock from a text file of "name,qty" lines. Record malformed lines instead of crashing, raise a custom exception when stock runs short, and return low-stock items with a dict comprehension.
- load(path) uses with and encoding="utf-8" and skips blank lines
- Record the line number of lines like "oil,abc" or lines with no comma in bad_lines
- remove(item, qty) raises OutOfStockError when asked for more than is left
- low_stock(limit) returns items with qty < limit using a dict comprehension
- Create the test file inside tempfile.TemporaryDirectory()
import os
import tempfile
class OutOfStockError(Exception):
# TODO: accept item, wanted, available and build a helpful message
...
class Inventory:
def __init__(self):
# TODO: an empty stock dict and an empty bad_lines list
...
def load(self, path):
# TODO: enumerate the lines from 1; skip blanks;
# split on ",", convert qty with int(); record bad line numbers
...
def remove(self, item, qty):
# TODO: raise OutOfStockError if qty is more than what is left
...
def low_stock(self, limit):
# TODO: dict comprehension of items whose qty is below limit
...
# TODO: write a small stock file in a temporary folder, load it, try two removalsExpected: rice, tea and sugar load, lines 3 and 6 are recorded as bad, the second removal of 3 tea fails with "tea: wanted 3, only 2 left", and low stock shows tea and sugar.
Show hint
name, qty = line.split(",") raises ValueError when there is no comma or more than one, and int("abc") raises ValueError too, so one except ValueError catches both kinds of bad line. enumerate(f, start=1) numbers the lines from 1.
Show solution
import os
import tempfile
class OutOfStockError(Exception):
def __init__(self, item, wanted, available):
super().__init__(f"{item}: wanted {wanted}, only {available} left")
class Inventory:
def __init__(self):
self.stock = {}
self.bad_lines = []
def load(self, path):
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
name, qty = line.split(",")
self.stock[name.strip()] = int(qty)
except ValueError:
self.bad_lines.append(number)
def remove(self, item, qty):
available = self.stock.get(item, 0)
if qty > available:
raise OutOfStockError(item, qty, available)
self.stock[item] = available - qty
def low_stock(self, limit):
return {name: qty for name, qty in self.stock.items() if qty < limit}
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "stock.csv")
with open(path, "w", encoding="utf-8") as f:
f.write("rice,40\ntea,5\noil,abc\n\nsugar,12\nbroken line\n")
inv = Inventory()
inv.load(path)
print("stock:", inv.stock)
print("bad lines:", inv.bad_lines)
try:
inv.remove("tea", 3)
inv.remove("tea", 3)
except OutOfStockError as err:
print("Error:", err)
print("low stock:", inv.low_stock(15))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class guards its own state by validating input inside its methods
- Raise a custom exception that carries data instead of printing an error
- finally runs even after a return; use with for file cleanup
- Open files with encoding="utf-8" and test them with tempfile
- sorted() is stable, so items with equal keys keep their original order
The Python Tutorial — Python Software Foundation