Lab

9.4.2. Lab#

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

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

  • Write and run your code directly in the coding cells.

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

Build an account service through validation, reporting, interest, importing, and comparison. Each stage includes its prerequisites so you can run it independently. Preserve the same contract throughout: nonnegative balance, read-only public balance, positive updates, and deposit/withdraw returning the account.

### Question 1: Establish the account contract
# Define BankAccount(owner, balance=0.0). Reject a negative starting balance
# with ValueError before storing it. Store owner and _balance; expose a
# read-only balance property. deposit(amount) accepts only positive amounts.
# withdraw(amount) accepts only positive amounts no greater than the balance.
# Both methods reject invalid operations with ValueError before mutation and
# return self after a successful update.
# Create account = BankAccount("Priya", 5000). Deposit 200 and withdraw 100.
# Try withdrawing 6000; catch ValueError and print "Withdrawal rejected".
# Then print the balance and whether deposit(1) returns account, as below:
# Withdrawal rejected
# Balance: 5100.00
# Returns account: True
### Your code starts here.


### Your code ends here.
### Question 2: Add account reports
# Extend the stage 1 BankAccount below with __str__ and __repr__.
# __str__ returns "owner: $balance" with two decimal places.
# __repr__ returns a reconstructable BankAccount(owner, balance) expression;
# use !r to preserve quotes in owner names.
# Create accounts = [BankAccount("Alice", 120.50), BankAccount("Bob", 75.0)].
# Print each account, then the list. Expected output:
# Alice: $120.50
# Bob: $75.00
# [BankAccount('Alice', 120.5), BankAccount('Bob', 75.0)]
# Add methods inside the class before writing the reporting code.
class BankAccount:
    def __init__(self, owner, balance=0.0):
        if balance < 0:
            raise ValueError("Starting balance cannot be negative")
        self.owner = owner
        self._balance = balance

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

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount
        return self

    def withdraw(self, amount):
        if amount <= 0 or amount > self._balance:
            raise ValueError("Invalid withdrawal")
        self._balance -= amount
        return self

### Your code starts here.


### Your code ends here.
### Question 3: Specialize the account service
# Use the stage 2 BankAccount below as the parent.
# Define MoneyMarketAccount(owner, balance=0.0, rate=0.02), calling
# super().__init__(owner, balance), and storing rate. Assume rate is nonnegative.
# apply_interest() deposits balance * rate when that amount is positive,
# leaves a zero-interest balance unchanged, and returns self.
# Use the public deposit method; do not assign to the read-only balance.
# Create account = MoneyMarketAccount("Priya", 5000, 0.02). Store its bound
# apply_interest method in action, then call action(). Print:
# Owner: Priya
# Balance after interest: 5100.00
class BankAccount:
    def __init__(self, owner, balance=0.0):
        if balance < 0:
            raise ValueError("Starting balance cannot be negative")
        self.owner = owner
        self._balance = balance

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

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount
        return self

    def withdraw(self, amount):
        if amount <= 0 or amount > self._balance:
            raise ValueError("Invalid withdrawal")
        self._balance -= amount
        return self

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

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

### Your code starts here.


### Your code ends here.
### Question 4: Import accounts through a factory
# Add from_string(cls, record) as a classmethod to the stage 2 BankAccount.
# The record has the form "owner:balance"; split it at the colon, convert the
# balance to float, and return cls(owner, balance). Assume well-formed records;
# negative balances must still be rejected by the initializer.
# Define StudentAccount(BankAccount) with no overridden initializer.
# Store StudentAccount.from_string in build and call build("Jordan:482.75").
# Print the following, including verification that the factory preserves the subclass:
# Owner: Jordan
# Balance: 482.75
# Student account: True
# Add the classmethod inside BankAccount before defining StudentAccount.
class BankAccount:
    def __init__(self, owner, balance=0.0):
        if balance < 0:
            raise ValueError("Starting balance cannot be negative")
        self.owner = owner
        self._balance = balance

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

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount
        return self

    def withdraw(self, amount):
        if amount <= 0 or amount > self._balance:
            raise ValueError("Invalid withdrawal")
        self._balance -= amount
        return self

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

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

### Your code starts here.


### Your code ends here.
### Question 5: Compare imported account balances
# Add __eq__ and __lt__ to the stage 4 BankAccount below.
# This report compares balances only, so different owners may compare equal.
# Return NotImplemented for an operand that is not a BankAccount.
# Use from_string to create a, b, c from "Alice:500", "Bob:500", "Charlie:200".
# Sort [a, b, c] and collect owner names in that order. Python's stable sort
# keeps Alice before Bob when their balances tie.
# Print the equality result, sorted owners, and a direct unsupported-type check:
# Equal balances: True
# Sorted owners: ['Charlie', 'Alice', 'Bob']
# Unsupported operand: True
# For the last line, test a.__eq__(500) is NotImplemented.
# Add comparison methods inside BankAccount before writing the report.
class BankAccount:
    def __init__(self, owner, balance=0.0):
        if balance < 0:
            raise ValueError("Starting balance cannot be negative")
        self.owner = owner
        self._balance = balance

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

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount
        return self

    def withdraw(self, amount):
        if amount <= 0 or amount > self._balance:
            raise ValueError("Invalid withdrawal")
        self._balance -= amount
        return self

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

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

    @classmethod
    def from_string(cls, record):
        owner, balance = record.split(":")
        return cls(owner, float(balance))

### Your code starts here.


### Your code ends here.