Lab

9.4.2. Lab#

  • Use this lab to practice the chapter’s coding skills in runnable Python code.

  • Sign in from the account menu before you start working on the lab.

  • Launch Live Code (the rocket) to write and run code in the coding cells.

  • Multiple submissions are allowed. The highest score is kept.

### Question 1: MoneyMarketAccount subclass
# BankAccount is defined below. Define MoneyMarketAccount as a
# subclass of BankAccount with __init__(self, owner, balance=0.0,
# rate=0.02) that calls super().__init__(owner, balance) and stores
# self.rate.
# Add a method apply_interest(self) that increases self.balance by
# self.balance * self.rate.
# Create account = MoneyMarketAccount("Priya", 5000, 0.02).
# Methods are values too: store the bound method in a variable named
# apply_interest, then call apply_interest() through that variable.
# Print exactly these two lines:
# Owner: Priya
# Balance after interest: 5100.00
class BankAccount:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class BankAccount:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

class MoneyMarketAccount(BankAccount):
    def __init__(self, owner, balance=0.0, rate=0.02):
        super().__init__(owner, balance)
        self.rate = rate

    def apply_interest(self):
        self.balance += self.balance * self.rate


account = MoneyMarketAccount("Priya", 5000, 0.02)
apply_interest = account.apply_interest
apply_interest()

print(f"Owner: {account.owner}")
print(f"Balance after interest: {account.balance:.2f}")
Owner: Priya
Balance after interest: 5100.00
### Question 2: Readable and unambiguous account display
# Define class BankAccount with __init__(self, owner, balance=0.0).
# Add __str__ returning "owner: $balance" with balance shown with
# 2 decimal places, for example "Alice: $120.50".
# Add __repr__ returning "BankAccount('owner', balance)", for
# example "BankAccount('Alice', 120.5)".
# Create accounts, a list holding BankAccount("Alice", 120.50) and
# BankAccount("Bob", 75.0).
# Loop over accounts and print each one (this uses __str__), then
# print accounts itself (this uses __repr__ for each element).
# Print exactly these three lines:
# Alice: $120.50
# Bob: $75.00
# [BankAccount('Alice', 120.5), BankAccount('Bob', 75.0)]
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class BankAccount:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

    def __str__(self):
        return f"{self.owner}: ${self.balance:.2f}"

    def __repr__(self):
        return f"BankAccount({self.owner!r}, {self.balance})"


accounts = [BankAccount("Alice", 120.50), BankAccount("Bob", 75.0)]

for account in accounts:
    print(account)

print(accounts)
Alice: $120.50
Bob: $75.00
[BankAccount('Alice', 120.5), BankAccount('Bob', 75.0)]
### Question 3: Balance after fee
# Define class BankAccount with a class attribute flat_fee = 5.0 and
# __init__(self, owner, balance=0.0) that stores balance in
# self._balance.
# Add a read-only property named balance that returns self._balance.
# Add a read-only property named balance_after_fee that returns
# self._balance - self.flat_fee.
# Create account = BankAccount("Sam", 250.0).
# Print exactly these two lines:
# Balance: 250.0
# Balance after fee: 245.0
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class BankAccount:
    flat_fee = 5.0

    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    @property
    def balance_after_fee(self):
        return self._balance - self.flat_fee


account = BankAccount("Sam", 250.0)

print("Balance:", account.balance)
print("Balance after fee:", account.balance_after_fee)
Balance: 250.0
Balance after fee: 245.0
### Question 4: from_string classmethod
# Define class BankAccount with __init__(self, owner, balance=0.0).
# Add a classmethod from_string(cls, owner, balance_str) that
# returns cls(owner, float(balance_str)).
# Classmethods are values too: store BankAccount.from_string in a
# variable named build, then call build("Jordan", "482.75") to
# create account.
# Print exactly these two lines:
# Owner: Jordan
# Balance: 482.75
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class BankAccount:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

    @classmethod
    def from_string(cls, owner, balance_str):
        return cls(owner, float(balance_str))


build = BankAccount.from_string
account = build("Jordan", "482.75")

print(f"Owner: {account.owner}")
print(f"Balance: {account.balance}")
Owner: Jordan
Balance: 482.75
### Question 5: Compare and sort accounts by balance
# Define class BankAccount with __init__(self, owner, balance=0.0).
# Add __eq__(self, other) that compares self.balance to
# other.balance.
# Add __lt__(self, other) that compares self.balance to
# other.balance.
# Create a = BankAccount("Alice", 500), b = BankAccount("Bob", 500),
# c = BankAccount("Charlie", 200), and accounts = [a, b, c].
# Build ordered by calling sorted(accounts), then owners as the list
# of owner names in that order.
# Print exactly these two lines:
# Equal balances: True
# Sorted owners: ['Charlie', 'Alice', 'Bob']
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class BankAccount:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

    def __eq__(self, other):
        return self.balance == other.balance

    def __lt__(self, other):
        return self.balance < other.balance


a = BankAccount("Alice", 500)
b = BankAccount("Bob", 500)
c = BankAccount("Charlie", 200)

accounts = [a, b, c]
ordered = sorted(accounts)
owners = [account.owner for account in ordered]

print("Equal balances:", a == b)
print("Sorted owners:", owners)
Equal balances: True
Sorted owners: ['Charlie', 'Alice', 'Bob']