Learn Python · lesson 44 of 60 · about 11 minutes
Project: Bike Fund
Model Sam's bike savings as an account class with deposits, safe withdrawals and a transaction history.
What you'll learn
- Design a class with state and methods
- Reject invalid actions
- Keep a history list
The bike fund
Sam's savings for the £120 bike become an Account in Sam's name that starts with what's already saved. Sam types commands until done: save 10 puts money in and spend 5 takes it out. deposit and withdraw refuse an amount that isn't more than 0, and withdraw refuses more than there is, by raising a ValueError with the reason; the loop catches it and prints Refused: only £55 saved. Every change goes in the history, and at the end the assistant prints the statement, Sam: £50 (+10, -5), and how much is still to go for the bike.
The design
An Account has:
- attributes: owner, balance and a history list
- methods: deposit, withdraw and statement
withdraw refuses to go below zero by raising a ValueError, and the caller catches it.
The account
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
self.history = []
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
self.history.append(f"+{amount}")
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Insufficient funds")
self.balance -= amount
self.history.append(f"-{amount}")
def statement(self):
return f"{self.owner}: £{self.balance} ({', '.join(self.history)})"
acc = Account("Ada")
acc.deposit(50)
acc.withdraw(20)
try:
acc.withdraw(100)
except ValueError as e:
print("Error:", e)
print(acc.statement())Output
Error: Insufficient funds
Ada: £30 (+50, -20)Tip
raise lets your own code signal a problem the same way Python's built-in errors do. The caller decides how to handle it.
Commands with a number
Each command is a word, a space and a number. command.partition(" ") splits it at the first space into three parts: the word, the space and the rest. Checking the word and amount.isdigit() first means int() only ever sees digits, so the only ValueErrors left are the account's own refusals, and except ValueError as e prints their message.
Splitting a command
for command in ["save 10", "spend", "save ten"]:
action, _, amount = command.partition(" ")
print(repr(action), repr(amount), amount.isdigit())Output
'save' '10' True
'spend' '' False
'save' 'ten' FalseNow try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.