Quick Thought
This exercise set takes things up a notch from Exercise Set 1, giving you a chance to combine Intermediate/Advanced chapter concepts like OOP (classes), error handling, file handling, and comprehensions into real hands-on problem-solving. In real projects, you rarely get to work with just one concept at a time — classes, exceptions, and file I/O usually show up together. That's why these tasks are designed to feel closer to that kind of real-world scenario. Solving them yourself and running the code will also sharpen your debugging skills.
Exercises
Task 1: Write a BankAccount class - it should have a balance attribute and two methods, deposit() and withdraw(). If someone tries to withdraw more than the balance, raise a custom exception called InsufficientFundsError. Task 2: Use try-except-finally to read a text file - if the file doesn't exist, catch the FileNotFoundError and print a friendly message. Either way, the finally block should always print "Read attempt finished". Task 3: Use a dictionary comprehension to build a {word: length} dictionary from a list of words, then sort and print the resulting dictionary by length.
Sample Code
# Task 1: BankAccount with custom exception
class InsufficientFundsError(Exception):
pass
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError("Not enough balance!")
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}")
# Task 2: safe file read
try:
with open("notes.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File not found, please check the filename.")
finally:
print("Read attempt finished")
# Task 3: dict comprehension + sort
words = ["python", "is", "fun", "and", "powerful"]
word_lengths = {w: len(w) for w in words}
sorted_words = dict(sorted(word_lengths.items(), key=lambda item: item[1]))
print(sorted_words)If you solve every task correctly, the output will show the withdraw error message plus the balance, the file-read result (or a friendly error), and a dictionary sorted by length.Try It: 5 Minutes
Set a 10-minute timer and write the BankAccount class from Task 1 yourself - try customizing the custom exception message with your own text.
A Quick Warning
When creating custom exceptions, be careful not to reuse the names of built-in exceptions. And remember, the finally block is always worth using for resource cleanup, like closing files or connections.