{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# Lab\n\n- Use this assignment to practice the chapter's concepts and coding skills in runnable Python code.\n- Sign in from the account menu before you start working on the assignment.\n- Write and run your code directly in the coding cells.\n- Multiple submissions are allowed. The highest score is kept.\n\n<div data-assignment-answers=\"ch09-lab\"></div>\n\nBuild 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.\n",
   "id": "ch09-lab-intro"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 1: Establish the account contract\n",
    "# Define BankAccount(owner, balance=0.0). Reject a negative starting balance\n",
    "# with ValueError before storing it. Store owner and _balance; expose a\n",
    "# read-only balance property. deposit(amount) accepts only positive amounts.\n",
    "# withdraw(amount) accepts only positive amounts no greater than the balance.\n",
    "# Both methods reject invalid operations with ValueError before mutation and\n",
    "# return self after a successful update.\n",
    "# Create account = BankAccount(\"Priya\", 5000). Deposit 200 and withdraw 100.\n",
    "# Try withdrawing 6000; catch ValueError and print \"Withdrawal rejected\".\n",
    "# Then print the balance and whether deposit(1) returns account, as below:\n",
    "# Withdrawal rejected\n",
    "# Balance: 5100.00\n",
    "# Returns account: True\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch09-lab-q1"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 2: Add account reports\n",
    "# Extend the stage 1 BankAccount below with __str__ and __repr__.\n",
    "# __str__ returns \"owner: $balance\" with two decimal places.\n",
    "# __repr__ returns a reconstructable BankAccount(owner, balance) expression;\n",
    "# use !r to preserve quotes in owner names.\n",
    "# Create accounts = [BankAccount(\"Alice\", 120.50), BankAccount(\"Bob\", 75.0)].\n",
    "# Print each account, then the list. Expected output:\n",
    "# Alice: $120.50\n",
    "# Bob: $75.00\n",
    "# [BankAccount('Alice', 120.5), BankAccount('Bob', 75.0)]\n",
    "# Add methods inside the class before writing the reporting code.\n",
    "class BankAccount:\n",
    "    def __init__(self, owner, balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError(\"Starting balance cannot be negative\")\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        return self._balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"Deposit must be positive\")\n",
    "        self._balance += amount\n",
    "        return self\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0 or amount > self._balance:\n",
    "            raise ValueError(\"Invalid withdrawal\")\n",
    "        self._balance -= amount\n",
    "        return self\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch09-lab-q2"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 3: Specialize the account service\n",
    "# Use the stage 2 BankAccount below as the parent.\n",
    "# Define MoneyMarketAccount(owner, balance=0.0, rate=0.02), calling\n",
    "# super().__init__(owner, balance), and storing rate. Assume rate is nonnegative.\n",
    "# apply_interest() deposits balance * rate when that amount is positive,\n",
    "# leaves a zero-interest balance unchanged, and returns self.\n",
    "# Use the public deposit method; do not assign to the read-only balance.\n",
    "# Create account = MoneyMarketAccount(\"Priya\", 5000, 0.02). Store its bound\n",
    "# apply_interest method in action, then call action(). Print:\n",
    "# Owner: Priya\n",
    "# Balance after interest: 5100.00\n",
    "class BankAccount:\n",
    "    def __init__(self, owner, balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError(\"Starting balance cannot be negative\")\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        return self._balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"Deposit must be positive\")\n",
    "        self._balance += amount\n",
    "        return self\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0 or amount > self._balance:\n",
    "            raise ValueError(\"Invalid withdrawal\")\n",
    "        self._balance -= amount\n",
    "        return self\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"{self.owner}: ${self.balance:.2f}\"\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f\"BankAccount({self.owner!r}, {self.balance!r})\"\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch09-lab-q3"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 4: Import accounts through a factory\n",
    "# Add from_string(cls, record) as a classmethod to the stage 2 BankAccount.\n",
    "# The record has the form \"owner:balance\"; split it at the colon, convert the\n",
    "# balance to float, and return cls(owner, balance). Assume well-formed records;\n",
    "# negative balances must still be rejected by the initializer.\n",
    "# Define StudentAccount(BankAccount) with no overridden initializer.\n",
    "# Store StudentAccount.from_string in build and call build(\"Jordan:482.75\").\n",
    "# Print the following, including verification that the factory preserves the subclass:\n",
    "# Owner: Jordan\n",
    "# Balance: 482.75\n",
    "# Student account: True\n",
    "# Add the classmethod inside BankAccount before defining StudentAccount.\n",
    "class BankAccount:\n",
    "    def __init__(self, owner, balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError(\"Starting balance cannot be negative\")\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        return self._balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"Deposit must be positive\")\n",
    "        self._balance += amount\n",
    "        return self\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0 or amount > self._balance:\n",
    "            raise ValueError(\"Invalid withdrawal\")\n",
    "        self._balance -= amount\n",
    "        return self\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"{self.owner}: ${self.balance:.2f}\"\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f\"BankAccount({self.owner!r}, {self.balance!r})\"\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch09-lab-q4"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 5: Compare imported account balances\n",
    "# Add __eq__ and __lt__ to the stage 4 BankAccount below.\n",
    "# This report compares balances only, so different owners may compare equal.\n",
    "# Return NotImplemented for an operand that is not a BankAccount.\n",
    "# Use from_string to create a, b, c from \"Alice:500\", \"Bob:500\", \"Charlie:200\".\n",
    "# Sort [a, b, c] and collect owner names in that order. Python's stable sort\n",
    "# keeps Alice before Bob when their balances tie.\n",
    "# Print the equality result, sorted owners, and a direct unsupported-type check:\n",
    "# Equal balances: True\n",
    "# Sorted owners: ['Charlie', 'Alice', 'Bob']\n",
    "# Unsupported operand: True\n",
    "# For the last line, test a.__eq__(500) is NotImplemented.\n",
    "# Add comparison methods inside BankAccount before writing the report.\n",
    "class BankAccount:\n",
    "    def __init__(self, owner, balance=0.0):\n",
    "        if balance < 0:\n",
    "            raise ValueError(\"Starting balance cannot be negative\")\n",
    "        self.owner = owner\n",
    "        self._balance = balance\n",
    "\n",
    "    @property\n",
    "    def balance(self):\n",
    "        return self._balance\n",
    "\n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"Deposit must be positive\")\n",
    "        self._balance += amount\n",
    "        return self\n",
    "\n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0 or amount > self._balance:\n",
    "            raise ValueError(\"Invalid withdrawal\")\n",
    "        self._balance -= amount\n",
    "        return self\n",
    "\n",
    "    def __str__(self):\n",
    "        return f\"{self.owner}: ${self.balance:.2f}\"\n",
    "\n",
    "    def __repr__(self):\n",
    "        return f\"BankAccount({self.owner!r}, {self.balance!r})\"\n",
    "\n",
    "    @classmethod\n",
    "    def from_string(cls, record):\n",
    "        owner, balance = record.split(\":\")\n",
    "        return cls(owner, float(balance))\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ],
   "id": "ch09-lab-q5"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "<style>\n.ch09-lab-grader { max-width: 900px; margin-top: 1rem; }\n.ch09-lab-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n.ch09-lab-feedback-list[hidden] { display: none; }\n.ch09-lab-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n.ch09-lab-feedback-row strong { margin-right: 0.35rem; }\n.ch09-lab-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n.ch09-lab-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n.ch09-lab-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n.ch09-lab-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n.ch09-lab-actions button.secondary { background: white; color: #176de8; }\n.ch09-lab-actions.is-locked { opacity: 0.55; }\n.ch09-lab-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n.ch09-lab-result { font-weight: 700; }\n</style>\n\n<div class='ch09-lab-grader' id='ch09-lab-grader'>\n  <div class='ch09-lab-feedback-list' aria-live='polite' hidden>\n    <div class='ch09-lab-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n    <div class='ch09-lab-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n    <div class='ch09-lab-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n    <div class='ch09-lab-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n    <div class='ch09-lab-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n  </div>\n  <div class='ch09-lab-actions'>\n    <button type='button' id='ch09-lab-submit' disabled>Submit</button>\n    <button type='button' class='secondary' id='ch09-lab-reset'>Clear Results</button>\n    <span class='ch09-lab-result' id='ch09-lab-result' aria-live='polite'></span>\n  </div>\n</div>\n\n<script>\n(function () {\n  var labId = 'ch09-lab';\n\n  function getParams() {\n    var params = new URLSearchParams(window.location.search);\n    return {\n      canvas_course_id: params.get('canvas_course_id') || params.get('course_id') || '',\n      canvas_assignment_id: params.get('canvas_assignment_id') || params.get('assignment_id') || '',\n      canvas_user_id: params.get('canvas_user_id') || params.get('user_id') || ''\n    };\n  }\n\n  function loadSessionIdentity(identity, actions, submit, result) {\n    submit.disabled = true;\n    actions.classList.add('is-locked');\n    result.textContent = 'Sign in from the account menu to submit this assignment.';\n    return fetch('/api/v1/session.php', { credentials: 'same-origin' })\n      .then(function (response) { return response.ok ? response.json() : null; })\n      .then(function (payload) {\n        if (!payload || !payload.authenticated || !payload.identity) return identity;\n        identity.canvas_user_id = payload.identity.canvas_user_id || identity.canvas_user_id || '';\n        identity.student_identifier = payload.identity.student_identifier || '';\n        submit.disabled = false;\n        actions.classList.remove('is-locked');\n        result.textContent = payload.identity.display_name ? 'Signed in as ' + payload.identity.display_name + '.' : 'Signed in.';\n        return identity;\n      })\n      .catch(function () { return identity; });\n  }\n\n  function codeFromCell(cell) {\n    var codeMirror = cell.querySelector('.CodeMirror');\n    if (codeMirror && codeMirror.CodeMirror && typeof codeMirror.CodeMirror.getValue === 'function') {\n      return codeMirror.CodeMirror.getValue();\n    }\n    var cmContent = cell.querySelector('.cm-content');\n    if (cmContent) {\n      return Array.from(cmContent.querySelectorAll('.cm-line')).map(function (line) { return line.textContent; }).join('\\n');\n    }\n    var textarea = cell.querySelector('textarea');\n    if (textarea) return textarea.value;\n    var pre = cell.querySelector('.cell_input pre');\n    return pre ? pre.textContent : '';\n  }\n\n  function collectCodeCells() {\n    var cells = Array.from(document.querySelectorAll('div.cell.tag_thebe-interactive')).slice(0, 5);\n    var code = {};\n    cells.forEach(function (cell, index) {\n      code['q' + (index + 1)] = codeFromCell(cell);\n    });\n    return code;\n  }\n\n  function applyFeedback(grader, feedback) {\n    var list = grader.querySelector('.ch09-lab-feedback-list');\n    if (list) list.hidden = false;\n    ['q1', 'q2', 'q3', 'q4', 'q5'].forEach(function (question) {\n      var row = grader.querySelector('[data-question=' + question + ']');\n      var message = row ? row.querySelector('span') : null;\n      var item = feedback ? feedback[question] : null;\n      if (!row || !message || !item) return;\n      row.classList.remove('correct', 'incorrect');\n      message.textContent = item.message + ' (' + item.score + ' / ' + item.max_score + ')';\n      row.classList.add(item.correct ? 'correct' : 'incorrect');\n    });\n  }\n\n  function clearFeedback(grader) {\n    var list = grader.querySelector('.ch09-lab-feedback-list');\n    if (list) list.hidden = true;\n    grader.querySelectorAll('.ch09-lab-feedback-row').forEach(function (row) {\n      row.classList.remove('correct', 'incorrect');\n      var message = row.querySelector('span');\n      if (message) message.textContent = '';\n    });\n  }\n\n  function saveAttempt(payload) {\n    return fetch('/api/v1/lab-attempts.php', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      credentials: 'same-origin',\n      body: JSON.stringify(payload)\n    }).then(function (response) {\n      return response.text().then(function (text) {\n        var saved = text ? JSON.parse(text) : null;\n        if (!response.ok || !saved || !saved.ok) throw new Error(saved && (saved.message || saved.error) ? (saved.message || saved.error) : 'Submission API is unavailable.');\n        return saved;\n      });\n    });\n  }\n\n  function initLabGrader() {\n    var grader = document.getElementById('ch09-lab-grader');\n    if (!grader || grader.dataset.ready === 'true') return;\n    grader.dataset.ready = 'true';\n\n    var identity = getParams();\n    var result = document.getElementById('ch09-lab-result');\n    var submit = document.getElementById('ch09-lab-submit');\n    var actions = grader.querySelector('.ch09-lab-actions');\n    var reset = document.getElementById('ch09-lab-reset');\n\n    loadSessionIdentity(identity, actions, submit, result);\n\n    submit.addEventListener('click', function () {\n      clearFeedback(grader);\n      result.textContent = 'Submitting code.';\n      submit.disabled = true;\n      saveAttempt({\n        lab_id: labId,\n        code: collectCodeCells(),\n        canvas_course_id: identity.canvas_course_id,\n        canvas_assignment_id: identity.canvas_assignment_id,\n        canvas_user_id: identity.canvas_user_id\n      })\n        .then(function (payload) {\n          if (payload.feedback) applyFeedback(grader, payload.feedback);\n          var best = (payload.best_score === null || typeof payload.best_score === 'undefined') ? payload.score : payload.best_score;\n          var attempt = (payload.attempt_count === null || typeof payload.attempt_count === 'undefined') ? '' : ' Attempt ' + payload.attempt_count + '.';\n          result.textContent = 'Submission saved.' + attempt + ' Score: ' + payload.score + ' / ' + payload.max_score + '. Best score: ' + best + ' / ' + payload.max_score + '. Canvas sync: ' + payload.canvas_sync_status + '.';\n        })\n        .catch(function (error) {\n          result.textContent = 'Could not save this attempt: ' + error.message;\n        })\n        .finally(function () {\n          submit.disabled = false;\n        });\n    });\n\n    reset.addEventListener('click', function () {\n      clearFeedback(grader);\n      result.textContent = '';\n    });\n  }\n\n  if (document.readyState === 'loading') {\n    document.addEventListener('DOMContentLoaded', initLabGrader);\n  } else {\n    initLabGrader();\n  }\n})();\n</script>\n",
   "id": "ch09-lab-submit-block"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11.0"
  },
  "press_solutions_stripped": true
 },
 "nbformat": 4,
 "nbformat_minor": 5
}