{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "t5-instructions",
   "metadata": {},
   "source": [
    "**Run the following cell before doing anything else** and then click the blue bar to the left of the cell to hide it, if it isn't already. Do **not** edit it!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-setup",
   "metadata": {
    "deletable": false,
    "editable": false,
    "init_cell": true,
    "jupyter": {
     "source_hidden": true
    },
    "tags": [
     "hide-input",
     "init_cell",
     "tutorial-setup"
    ]
   },
   "outputs": [],
   "source": [
    "from IPython import get_ipython\n",
    "from IPython.display import HTML, Javascript, clear_output, display\n",
    "import hashlib\n",
    "import hmac\n",
    "import html\n",
    "import json\n",
    "\n",
    "_TUTORIAL_CHECK_ORDER = ['1.0.1',\n",
    " '2.1.1',\n",
    " '2.2.1',\n",
    " '3.1.1',\n",
    " '3.2.1',\n",
    " '3.3.1',\n",
    " '3.4.1',\n",
    " '3.5.1',\n",
    " '4.1.1',\n",
    " '4.2.1',\n",
    " '4.3.1',\n",
    " '4.4.1',\n",
    " '5.1.1',\n",
    " '5.2.1',\n",
    " '5.3.1']\n",
    "_TUTORIAL_PROGRESS_IDS = {}\n",
    "_TUTORIAL_CHECK_BRANCHES = {}\n",
    "_TUTORIAL_TEXT_CHECKS = {'4.4.1', '5.1.1', '1.0.1', '5.2.1', '4.3.1', '4.2.1', '5.3.1', '4.1.1'}\n",
    "_TUTORIAL_OPTIONAL_NOTES = {'6.1.1', '6.3.1', '6.2.1'}\n",
    "_TUTORIAL_EXACT_CHECKS = {'2.1.1': ('1cdd9da2e3bf188a80340ef4ca327009308eac13fce2a43d909ab7848f9049db',\n",
    "           'Run the original buggy_cafe.py and paste its single output line, including the £ sign '\n",
    "           'and two decimal places.'),\n",
    " '2.2.1': ('7c5547607a58e1efbcbef124f23dac33b82913d44b900f9e8a29a8c39d4de08c',\n",
    "           'Pause on the subtotal assignment in receipt, select its frame in CALL STACK, and '\n",
    "           'evaluate prices in the Debug Console.'),\n",
    " '3.1.1': ('b373e3283c94fc22ef6a162f040461b4c79c76556b7c46c862e389c61a8fa2f6',\n",
    "           'Stop BEFORE the first total = price executes. Select basket_total in CALL STACK, then '\n",
    "           'evaluate price, total.'),\n",
    " '3.2.1': ('abccea704e52e771bb4e489186f0c42a222fabd6b84632e7eac1595006f4dcec',\n",
    "           'Record total AFTER each execution of total = price in the unchanged program. Paste '\n",
    "           'three numbers, each on its own line.'),\n",
    " '3.3.1': ('4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a',\n",
    "           'Finish the subtotal assignment in receipt, then evaluate subtotal. The original '\n",
    "           'basket_total has not been repaired yet.'),\n",
    " '3.4.1': ('d242dd4adead0c75f49d92244b996a510db00d940a4752540490a4bf7c0e066e',\n",
    "           'Repair only the accumulation in basket_total, leaving receipt unchanged for now. Run '\n",
    "           'all three assertions, then paste the printed receipt.'),\n",
    " '3.5.1': ('3b34c2bd05af2b5d876ac43783cb100f65868f569ef90c7dbd7e8bf80e3e77b5',\n",
    "           'Check the free-delivery boundary, save both repairs, and use the supplied main(). '\n",
    "           'Paste both output lines.')}\n",
    "_TUTORIAL_STARTER_ANSWERS = {'1.0.1': 'WRITE NAMES HERE',\n",
    " '2.1.1': 'PASTE OUTPUT HERE',\n",
    " '2.2.1': 'PASTE OUTPUT HERE',\n",
    " '3.1.1': 'PASTE OUTPUT HERE',\n",
    " '3.2.1': 'PASTE OUTPUT HERE',\n",
    " '3.3.1': 'PASTE OUTPUT HERE',\n",
    " '3.4.1': 'PASTE OUTPUT HERE',\n",
    " '3.5.1': 'PASTE OUTPUT HERE',\n",
    " '4.1.1': 'WRITE NOTES HERE',\n",
    " '4.2.1': 'WRITE NOTES HERE',\n",
    " '4.3.1': 'WRITE NOTES HERE',\n",
    " '4.4.1': 'WRITE NOTES HERE',\n",
    " '5.1.1': 'WRITE NOTES HERE',\n",
    " '5.2.1': 'WRITE NOTES HERE',\n",
    " '5.3.1': 'WRITE NOTES HERE',\n",
    " '6.1.1': 'WRITE NOTES HERE',\n",
    " '6.2.1': 'WRITE NOTES HERE',\n",
    " '6.3.1': 'WRITE NOTES HERE'}\n",
    "_TUTORIAL_SUCCESS_MESSAGES = {'1.0.1': ('Notes recorded.', 'Your debugging team is ready. Keep the moths outside.'),\n",
    " '2.1.1': ('Correct!', 'That is what the broken program prints. Now let us find out why.'),\n",
    " '2.2.1': ('Correct!', 'You are looking at the actual values in a paused program.'),\n",
    " '3.1.1': ('Correct!', 'The price is 3, but the assignment has not yet changed total.'),\n",
    " '3.2.1': ('Correct!', 'You have located the first point where the running total goes wrong.'),\n",
    " '3.3.1': ('Correct!', 'The wrong subtotal explains how the error reaches the receipt.'),\n",
    " '3.4.1': ('Correct!', 'The subtotal checks pass. The final bill still needs investigating.'),\n",
    " '3.5.1': ('Correct!',\n",
    "           'The café can now charge for snacks without charging extra for our mistakes. Time to '\n",
    "           'make your own bugs!'),\n",
    " '4.1.1': ('Notes recorded.',\n",
    "           'Your specification gives the other pair something definite to check.'),\n",
    " '4.2.1': ('Notes recorded.',\n",
    "           'Keep that working copy. It is your reference for the bugs you are about to introduce.'),\n",
    " '4.3.1': ('Notes recorded.',\n",
    "           'You now have three explainable bugs, with evidence and hints for each.'),\n",
    " '4.4.1': ('Notes recorded.',\n",
    "           'The receiving pair has the intended behaviour and reproducible examples. Time to swap '\n",
    "           'roles.'),\n",
    " '5.1.1': ('Notes recorded.', 'You have a reproducible problem and a first place to look.'),\n",
    " '5.2.1': ('Notes recorded.', 'Your investigation log connects each repair to an observation.'),\n",
    " '5.3.1': ('Notes recorded.',\n",
    "           'You have completed the core tutorial! Choose any bonus task if there is time.'),\n",
    " '6.1.1': ('Notes recorded.', 'Continue to the next step.'),\n",
    " '6.2.1': ('Notes recorded.', 'Continue to the next step.'),\n",
    " '6.3.1': ('Notes recorded.', 'Continue to the next step.')}\n",
    "\n",
    "# Only inherit progress when this setup belongs to the same tutorial.\n",
    "# A different notebook may have used this kernel before us.\n",
    "_tutorial_same_identity = (\n",
    "    globals().get(\"_TUTORIAL_IDENTITY\") == \"tutorial-5-bug-your-own-tutorial\"\n",
    "    and getattr(globals().get(\"_tutorial_check\"), \"_tutorial_identity\", None) == \"tutorial-5-bug-your-own-tutorial\"\n",
    ")\n",
    "_previous_completed = set(globals().get(\"_TUTORIAL_COMPLETED\", set())) if _tutorial_same_identity else set()\n",
    "_TUTORIAL_IDENTITY = \"tutorial-5-bug-your-own-tutorial\"\n",
    "_TUTORIAL_COMPLETED = set()\n",
    "for _check_id in _TUTORIAL_CHECK_ORDER:\n",
    "    if _check_id not in _previous_completed:\n",
    "        break\n",
    "    _TUTORIAL_COMPLETED.add(_check_id)\n",
    "_TUTORIAL_COMPLETED.update(_previous_completed & _TUTORIAL_OPTIONAL_NOTES)\n",
    "_TUTORIAL_SELECTIONS = {}\n",
    "\n",
    "\n",
    "def _tutorial_progress_id(check_id):\n",
    "    return _TUTORIAL_PROGRESS_IDS.get(check_id, check_id)\n",
    "\n",
    "\n",
    "def _tutorial_reset_progress(expected_identity=\"tutorial-5-bug-your-own-tutorial\"):\n",
    "    if expected_identity != _TUTORIAL_IDENTITY:\n",
    "        return False\n",
    "    _TUTORIAL_COMPLETED.clear()\n",
    "    _TUTORIAL_SELECTIONS.clear()\n",
    "    return True\n",
    "\n",
    "\n",
    "def _tutorial_normalize(value):\n",
    "    return \"\\n\".join(line.rstrip() for line in value.strip().splitlines())\n",
    "\n",
    "\n",
    "def _tutorial_digest(value):\n",
    "    return hashlib.sha256(value.encode(\"utf-8\")).hexdigest()\n",
    "\n",
    "\n",
    "def _tutorial_message(kind, title, message):\n",
    "    colours = {\n",
    "        \"correct\": (\"#166534\", \"#dcfce7\", \"#86efac\"),\n",
    "        \"incorrect\": (\"#991b1b\", \"#fef2f2\", \"#fca5a5\"),\n",
    "    }\n",
    "    text, background, border = colours[kind]\n",
    "    display(HTML(\n",
    "        f'<div style=\"margin:8px 0;padding:10px 12px;border-left:4px solid {border};'\n",
    "        f'background:{background};color:{text}\">'\n",
    "        f'<strong>{html.escape(title)}</strong> {html.escape(message)}</div>'\n",
    "    ))\n",
    "\n",
    "\n",
    "def _tutorial_check(line, cell, _identity=\"tutorial-5-bug-your-own-tutorial\"):\n",
    "    clear_output(wait=True)\n",
    "    if _identity != _TUTORIAL_IDENTITY:\n",
    "        _tutorial_message(\"incorrect\", \"Run this tutorial's setup first.\", \"This kernel is currently checking a different tutorial.\")\n",
    "        return\n",
    "    check_id = line.strip()\n",
    "    progress_id = _tutorial_progress_id(check_id)\n",
    "    answer = _tutorial_normalize(cell)\n",
    "    known_checks = set(_TUTORIAL_CHECK_ORDER) | _TUTORIAL_OPTIONAL_NOTES\n",
    "\n",
    "    if check_id not in known_checks:\n",
    "        _tutorial_message(\"incorrect\", \"This check could not run.\", \"Please ask your tutor for help.\")\n",
    "        return\n",
    "\n",
    "    placeholders = tuple(value.upper() for value in _TUTORIAL_STARTER_ANSWERS.values())\n",
    "    if not answer or any(placeholder in answer.upper() for placeholder in placeholders):\n",
    "        _tutorial_message(\"incorrect\", \"No answer yet.\", \"Replace the placeholder, then run the cell again.\")\n",
    "        return\n",
    "\n",
    "    if progress_id in _TUTORIAL_CHECK_ORDER:\n",
    "        position = _TUTORIAL_CHECK_ORDER.index(progress_id)\n",
    "        missing = [\n",
    "            earlier for earlier in _TUTORIAL_CHECK_ORDER[:position]\n",
    "            if earlier not in _TUTORIAL_COMPLETED\n",
    "        ]\n",
    "        if missing:\n",
    "            _tutorial_message(\"incorrect\", \"Complete the previous step first.\", \"Return to the last visible check above.\")\n",
    "            return\n",
    "\n",
    "    correct = False\n",
    "    hint = \"Check your answer carefully and try again.\"\n",
    "    completion_details = {}\n",
    "\n",
    "    if check_id in _TUTORIAL_EXACT_CHECKS:\n",
    "        expected_digest, hint = _TUTORIAL_EXACT_CHECKS[check_id]\n",
    "        correct = hmac.compare_digest(_tutorial_digest(answer), expected_digest)\n",
    "    elif check_id in _TUTORIAL_TEXT_CHECKS or check_id in _TUTORIAL_OPTIONAL_NOTES:\n",
    "        correct = bool(answer)\n",
    "        hint = \"Write something before running the cell.\"\n",
    "\n",
    "    if not correct:\n",
    "        _tutorial_message(\"incorrect\", \"Not quite.\", hint)\n",
    "        return\n",
    "\n",
    "    already_completed = progress_id in _TUTORIAL_COMPLETED\n",
    "    if progress_id in _TUTORIAL_CHECK_ORDER and not already_completed:\n",
    "        position = _TUTORIAL_CHECK_ORDER.index(progress_id)\n",
    "        for later_id in _TUTORIAL_CHECK_ORDER[position + 1:]:\n",
    "            _TUTORIAL_COMPLETED.discard(later_id)\n",
    "        completion_details[\"resetFollowing\"] = True\n",
    "\n",
    "    _TUTORIAL_COMPLETED.add(progress_id)\n",
    "\n",
    "    if check_id in _TUTORIAL_OPTIONAL_NOTES:\n",
    "        _tutorial_message(\"correct\", \"Notes recorded.\", \"You can continue with any bonus task.\")\n",
    "        return\n",
    "\n",
    "    title, message = _TUTORIAL_SUCCESS_MESSAGES.get(check_id, (\"Correct!\", \"\"))\n",
    "    _tutorial_message(\"correct\", title, message)\n",
    "    display(Javascript(\n",
    "        \"window.__tutorialProgress && window.__tutorialProgress.complete(\"\n",
    "        + json.dumps(check_id)\n",
    "        + \", \"\n",
    "        + json.dumps(completion_details)\n",
    "        + \");\"\n",
    "    ))\n",
    "\n",
    "\n",
    "_tutorial_check._tutorial_identity = _TUTORIAL_IDENTITY\n",
    "_tutorial_shell = get_ipython()\n",
    "if _tutorial_shell is None:\n",
    "    raise RuntimeError(\"Run this cell with a Python Jupyter kernel.\")\n",
    "_tutorial_shell.register_magic_function(_tutorial_check, \"cell\", \"check\")\n",
    "_tutorial_message(\"correct\", \"Setup complete.\", \"Your debugging tutorial checks are ready.\")\n",
    "\n",
    "\n",
    "_tutorial_progress_javascript = r\"\"\"\n",
    "(() => {\n",
    "  const tutorialIdentity = \"tutorial-5-bug-your-own-tutorial\";\n",
    "  const checkOrder = __CHECK_ORDER__;\n",
    "  const progressIds = __PROGRESS_IDS__;\n",
    "  const checkBranches = __CHECK_BRANCHES__;\n",
    "  const optionalNotes = __OPTIONAL_NOTES__;\n",
    "  const completedFromKernel = __COMPLETED__;\n",
    "  const selectionsFromKernel = __SELECTIONS__;\n",
    "  const hiddenClass = \"tutorial-progress-hidden\";\n",
    "  const styleId = \"tutorial-progress-style\";\n",
    "  const starterAnswers = __STARTER_ANSWERS__;\n",
    "\n",
    "  if (!document.getElementById(styleId)) {\n",
    "    const style = document.createElement(\"style\");\n",
    "    style.id = styleId;\n",
    "    style.textContent = `.${hiddenClass} { display: none !important; }`;\n",
    "    document.head.appendChild(style);\n",
    "  }\n",
    "\n",
    "  const previous = window.__tutorialProgress;\n",
    "  if (previous && previous.observer) previous.observer.disconnect();\n",
    "\n",
    "  const state = {\n",
    "    completed: new Set(completedFromKernel),\n",
    "    selections: { ...selectionsFromKernel },\n",
    "    observer: null,\n",
    "    scheduled: false,\n",
    "  };\n",
    "\n",
    "  function progressId(id) {\n",
    "    return progressIds[id] || id;\n",
    "  }\n",
    "\n",
    "  function visibleNotebook() {\n",
    "    const scriptNotebook = document.currentScript &&\n",
    "      document.currentScript.closest(\".jp-Notebook, #notebook-container\");\n",
    "    if (scriptNotebook) return scriptNotebook;\n",
    "    const candidates = [...document.querySelectorAll(\".jp-Notebook, #notebook-container\")];\n",
    "    return candidates.find((node) => node.offsetParent !== null) || candidates[0] || null;\n",
    "  }\n",
    "\n",
    "  function currentNotebookPanel() {\n",
    "    const apps = [\n",
    "      window.jupyterapp,\n",
    "      window.jupyterlab,\n",
    "      window.jupyterLab,\n",
    "      window.jupyterFrontEnd,\n",
    "      window.jupyterApp,\n",
    "    ];\n",
    "    for (const app of apps) {\n",
    "      const widget = app && app.shell && app.shell.currentWidget;\n",
    "      if (widget && widget.content && widget.content.model && widget.context) return widget;\n",
    "    }\n",
    "    return null;\n",
    "  }\n",
    "\n",
    "  state.notebook = visibleNotebook();\n",
    "\n",
    "  if (!state.notebook) {\n",
    "    const warning = document.createElement(\"div\");\n",
    "    warning.style.cssText = \"margin:8px 0;padding:10px 12px;border-left:4px solid #f59e0b;background:#fffbeb;color:#92400e;font-family:system-ui,sans-serif\";\n",
    "    warning.textContent = \"The checks are ready, but this notebook frontend does not allow automatic section reveal. The checks will still mark answers, but all sections may remain visible.\";\n",
    "    document.body.appendChild(warning);\n",
    "    return;\n",
    "  }\n",
    "\n",
    "  state.notebook.__tutorialProgress = state;\n",
    "\n",
    "  function cells() {\n",
    "    const selector = state.notebook.id === \"notebook-container\"\n",
    "      ? \":scope > .cell\"\n",
    "      : \".jp-Notebook-cell\";\n",
    "    return [...state.notebook.querySelectorAll(selector)].filter(\n",
    "      (cell) => !cell.closest(\".jp-Notebook\") || cell.closest(\".jp-Notebook\") === state.notebook\n",
    "    );\n",
    "  }\n",
    "\n",
    "  function source(cell) {\n",
    "    const classicEditor = cell.querySelector(\".CodeMirror\");\n",
    "    if (classicEditor && classicEditor.CodeMirror) return classicEditor.CodeMirror.getValue();\n",
    "    const modernEditor = cell.querySelector(\".cm-content\");\n",
    "    if (modernEditor) return modernEditor.innerText || modernEditor.textContent || \"\";\n",
    "    const input = cell.querySelector(\".input_area, .jp-InputArea-editor\");\n",
    "    return input ? (input.innerText || input.textContent || \"\") : \"\";\n",
    "  }\n",
    "\n",
    "  function checkId(cell) {\n",
    "    const match = source(cell).match(/^%%check\\s+([a-z0-9_.-]+)/m);\n",
    "    return match ? match[1] : null;\n",
    "  }\n",
    "\n",
    "  function renderedMarker(cell) {\n",
    "    return cell.querySelector(\"[data-tutorial-section]\");\n",
    "  }\n",
    "\n",
    "  function explicitSectionNumber(cell) {\n",
    "    const sectionMarker = renderedMarker(cell);\n",
    "    if (sectionMarker) return Number(sectionMarker.dataset.tutorialSection);\n",
    "    const markerMatch = source(cell).match(/data-tutorial-section=[\\\"'](\\d+)[\\\"']/);\n",
    "    if (markerMatch) return Number(markerMatch[1]);\n",
    "    const id = checkId(cell);\n",
    "    const progress = id ? progressId(id) : null;\n",
    "    const checkIndex = progress ? checkOrder.indexOf(progress) : -1;\n",
    "    if (checkIndex >= 0) return checkIndex;\n",
    "    if (id && optionalNotes.includes(id)) return checkOrder.length;\n",
    "    return null;\n",
    "  }\n",
    "\n",
    "  function sectionNumber(cell, notebookCells) {\n",
    "    const ownSection = explicitSectionNumber(cell);\n",
    "    if (ownSection !== null) return ownSection;\n",
    "    const index = notebookCells.indexOf(cell);\n",
    "    for (let cursor = index - 1; cursor >= 0; cursor -= 1) {\n",
    "      const inheritedSection = explicitSectionNumber(notebookCells[cursor]);\n",
    "      if (inheritedSection !== null) return inheritedSection;\n",
    "    }\n",
    "    return 0;\n",
    "  }\n",
    "\n",
    "  function branch(cell) {\n",
    "    const sectionMarker = renderedMarker(cell);\n",
    "    if (sectionMarker && sectionMarker.dataset.tutorialOs) {\n",
    "      return {\n",
    "        software: sectionMarker.dataset.tutorialSoftware,\n",
    "        os: sectionMarker.dataset.tutorialOs,\n",
    "      };\n",
    "    }\n",
    "    const id = checkId(cell);\n",
    "    if (id && checkBranches[id]) return checkBranches[id];\n",
    "    const cellSource = source(cell);\n",
    "    const software = cellSource.match(/data-tutorial-software=[\\\"']([^\\\"']+)[\\\"']/);\n",
    "    const os = cellSource.match(/data-tutorial-os=[\\\"']([^\\\"']+)[\\\"']/);\n",
    "    return software && os ? { software: software[1], os: os[1] } : null;\n",
    "  }\n",
    "\n",
    "  function refresh() {\n",
    "    state.scheduled = false;\n",
    "    let unlockedSection = 0;\n",
    "    for (const id of checkOrder) {\n",
    "      if (!state.completed.has(id)) break;\n",
    "      unlockedSection += 1;\n",
    "    }\n",
    "    const notebookCells = cells();\n",
    "    for (const cell of notebookCells) {\n",
    "      const requiredBranch = branch(cell);\n",
    "      const wrongBranch = requiredBranch &&\n",
    "        state.selections[requiredBranch.software] !== requiredBranch.os;\n",
    "      const locked = sectionNumber(cell, notebookCells) > unlockedSection;\n",
    "      cell.classList.toggle(hiddenClass, Boolean(locked || wrongBranch));\n",
    "    }\n",
    "    bindResetButtons();\n",
    "    window.dispatchEvent(new Event(\"resize\"));\n",
    "  }\n",
    "\n",
    "  function scheduleRefresh() {\n",
    "    if (state.scheduled) return;\n",
    "    state.scheduled = true;\n",
    "    requestAnimationFrame(refresh);\n",
    "  }\n",
    "\n",
    "  state.complete = (id, details = {}) => {\n",
    "    const progress = progressId(id);\n",
    "    if (!checkOrder.includes(progress)) return;\n",
    "    const position = checkOrder.indexOf(progress);\n",
    "    if (details.resetFollowing) {\n",
    "      for (const laterId of checkOrder.slice(position + 1)) state.completed.delete(laterId);\n",
    "    }\n",
    "    state.completed.add(progress);\n",
    "    if (details.software && details.os) state.selections[details.software] = details.os;\n",
    "    refresh();\n",
    "  };\n",
    "\n",
    "\n",
    "  function starterSource(id) {\n",
    "    return `%%check ${id}\\n${starterAnswers[id]}`;\n",
    "  }\n",
    "\n",
    "  function modelSource(cell) {\n",
    "    if (cell.sharedModel && cell.sharedModel.getSource) return cell.sharedModel.getSource();\n",
    "    if (cell.value && typeof cell.value.text === \"string\") return cell.value.text;\n",
    "    return \"\";\n",
    "  }\n",
    "\n",
    "  function clearDomOutput(cellNode) {\n",
    "    for (const output of cellNode.querySelectorAll(\".output, .output_wrapper, .jp-OutputArea, .jp-Cell-outputArea\")) {\n",
    "      output.replaceChildren();\n",
    "    }\n",
    "  }\n",
    "\n",
    "  function resetDomCheckCells() {\n",
    "    let resetCount = 0;\n",
    "    for (const cellNode of cells()) {\n",
    "      const id = checkId(cellNode);\n",
    "      if (!id || !starterAnswers[id]) continue;\n",
    "      const sourceText = starterSource(id);\n",
    "      const classicEditor = cellNode.querySelector(\".CodeMirror\");\n",
    "      if (classicEditor && classicEditor.CodeMirror) {\n",
    "        classicEditor.CodeMirror.setValue(sourceText);\n",
    "        clearDomOutput(cellNode);\n",
    "        resetCount += 1;\n",
    "      }\n",
    "    }\n",
    "    return resetCount;\n",
    "  }\n",
    "\n",
    "  async function resetNotebookCells() {\n",
    "    const classicNotebook = window.Jupyter && window.Jupyter.notebook;\n",
    "    if (classicNotebook && classicNotebook.get_cells) {\n",
    "      for (const cell of classicNotebook.get_cells()) {\n",
    "        const match = cell.get_text().match(/^%%check\\s+([a-z0-9_.-]+)/m);\n",
    "        if (!match || !starterAnswers[match[1]]) continue;\n",
    "        cell.set_text(starterSource(match[1]));\n",
    "        if (cell.clear_output) cell.clear_output();\n",
    "        if (cell.set_input_prompt) cell.set_input_prompt(null);\n",
    "      }\n",
    "      classicNotebook.set_dirty(true);\n",
    "      await classicNotebook.save_notebook();\n",
    "      return;\n",
    "    }\n",
    "\n",
    "    const panel = currentNotebookPanel();\n",
    "    const notebookModel = panel && panel.content && panel.content.model;\n",
    "    if (notebookModel && notebookModel.cells) {\n",
    "      for (let index = 0; index < notebookModel.cells.length; index += 1) {\n",
    "        const cell = notebookModel.cells.get(index);\n",
    "        const match = modelSource(cell).match(/^%%check\\s+([a-z0-9_.-]+)/m);\n",
    "        if (!match || !starterAnswers[match[1]]) continue;\n",
    "        if (cell.sharedModel && cell.sharedModel.setSource) {\n",
    "          cell.sharedModel.setSource(starterSource(match[1]));\n",
    "        } else if (cell.value && typeof cell.value.text === \"string\") {\n",
    "          cell.value.text = starterSource(match[1]);\n",
    "        }\n",
    "        if (cell.outputs && cell.outputs.clear) cell.outputs.clear();\n",
    "        if (\"executionCount\" in cell) cell.executionCount = null;\n",
    "      }\n",
    "      await panel.context.save();\n",
    "      return;\n",
    "    }\n",
    "\n",
    "    if (resetDomCheckCells() > 0) return;\n",
    "\n",
    "    throw new Error(\"This notebook frontend does not expose a writable notebook model.\");\n",
    "  }\n",
    "\n",
    "  async function resetKernelProgress() {\n",
    "    const code = \"_tutorial_reset_progress(\\\"\" + tutorialIdentity + \"\\\")\";\n",
    "    try {\n",
    "      const classicKernel = window.Jupyter && window.Jupyter.notebook && window.Jupyter.notebook.kernel;\n",
    "      if (classicKernel && classicKernel.execute) {\n",
    "        classicKernel.execute(code, {}, { silent: true, store_history: false });\n",
    "        return true;\n",
    "      }\n",
    "\n",
    "      const panel = currentNotebookPanel();\n",
    "      const kernel = panel && panel.sessionContext && panel.sessionContext.session &&\n",
    "        panel.sessionContext.session.kernel;\n",
    "      if (kernel && kernel.requestExecute) {\n",
    "        const future = kernel.requestExecute({ code, silent: true, store_history: false });\n",
    "        await future.done;\n",
    "        return true;\n",
    "      }\n",
    "    } catch (error) {\n",
    "      console.error(\"Could not reset tutorial kernel state\", error);\n",
    "    }\n",
    "    return false;\n",
    "  }\n",
    "\n",
    "  async function resetProgress(button) {\n",
    "    const confirmed = window.confirm(\n",
    "      \"Reset all tutorial progress? Every answer and check result will be cleared.\"\n",
    "    );\n",
    "    if (!confirmed) return;\n",
    "\n",
    "    button.disabled = true;\n",
    "    button.textContent = \"Resetting…\";\n",
    "    try {\n",
    "      await resetNotebookCells();\n",
    "      const kernelWasReset = await resetKernelProgress();\n",
    "      state.completed.clear();\n",
    "      state.selections = {};\n",
    "      refresh();\n",
    "      state.notebook.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n",
    "      button.disabled = false;\n",
    "      button.textContent = \"Reset all tutorial progress\";\n",
    "      if (kernelWasReset) {\n",
    "        window.alert(\"Tutorial progress has been reset.\");\n",
    "      } else {\n",
    "        window.alert(\n",
    "          \"Answers were reset. Restart the kernel before beginning again to clear its saved progress too.\"\n",
    "        );\n",
    "      }\n",
    "    } catch (error) {\n",
    "      console.error(\"Could not reset tutorial progress\", error);\n",
    "      window.alert(`The tutorial could not be reset: ${error.message}`);\n",
    "      button.disabled = false;\n",
    "      button.textContent = \"Reset all tutorial progress\";\n",
    "    }\n",
    "  }\n",
    "\n",
    "  function bindResetButtons() {\n",
    "    for (const button of state.notebook.querySelectorAll(\"[data-tutorial-reset]\")) {\n",
    "      if (button.dataset.tutorialResetBound) continue;\n",
    "      button.dataset.tutorialResetBound = \"true\";\n",
    "      button.addEventListener(\"click\", () => state.notebook.__tutorialProgress.reset(button));\n",
    "    }\n",
    "  }\n",
    "\n",
    "  state.reset = resetProgress;\n",
    "  state.observer = new MutationObserver(scheduleRefresh);\n",
    "  state.observer.observe(state.notebook, { childList: true, subtree: true });\n",
    "  window.__tutorialProgress = state;\n",
    "  refresh();\n",
    "  setTimeout(refresh, 100);\n",
    "  setTimeout(refresh, 500);\n",
    "  setTimeout(refresh, 1500);\n",
    "})();\n",
    "\"\"\".replace(\"__STARTER_ANSWERS__\", json.dumps(_TUTORIAL_STARTER_ANSWERS)).replace(\"__CHECK_ORDER__\", json.dumps(_TUTORIAL_CHECK_ORDER)).replace(\n",
    "    \"__PROGRESS_IDS__\", json.dumps(_TUTORIAL_PROGRESS_IDS)\n",
    ").replace(\n",
    "    \"__CHECK_BRANCHES__\", json.dumps(_TUTORIAL_CHECK_BRANCHES)\n",
    ").replace(\n",
    "    \"__OPTIONAL_NOTES__\", json.dumps(sorted(_TUTORIAL_OPTIONAL_NOTES))\n",
    ").replace(\n",
    "    \"__COMPLETED__\", json.dumps(sorted(_TUTORIAL_COMPLETED))\n",
    ").replace(\n",
    "    \"__SELECTIONS__\", json.dumps(_TUTORIAL_SELECTIONS)\n",
    ")\n",
    "\n",
    "display(Javascript(_tutorial_progress_javascript))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-02",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"0\" hidden></span>\n",
    "\n",
    "# Tutorial 5: Bug Your Own Tutorial\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "Week 8 | Author: Rayo Verweij (<code>rayo.verweij@ed.ac.uk</code>)<br>\n",
    "</div>\n",
    "\n",
    "Welcome back! Now that our programs are getting more complex, it's time to look into more complex bug-catching tools as well. Modern editors such as VS Code have advanced **debugger** functionality that we will explore in this tutorial.\n",
    "\n",
    "Using the word *bug* to describe a fault in a machine goes back to electrical engineers in the 19th century, who probably were not thinking about animals but rather as errors *bugging* them. In September 1947, however, the meanings famously coalesced as the team working on the Harvard Mark II computer found a moth trapped in a relay. They taped it into the logbook, with the comment **“First actual case of bug being found.”** Grace Hopper, who worked with the team, helped make the story famous and soon the words *bug* and *debugging* were everywhere. The [Smithsonian preserves the famous logbook page](https://americanhistory.si.edu/collections/object/nmah_334663).\n",
    "\n",
    "Fortunately, today's bugs can be removed without touching any insects.\n",
    "\n",
    "This tutorial has **two halves**. In sections 2–3, you will try out the VS Code debugger to investigate a bugged program. In sections 4–5, you will design a program, introduce some bugs, and exchange it with others in the tutorial for them to fix. Leave roughly half your working time for that second half!\n",
    "\n",
    "---\n",
    "\n",
    "## 1 Introductions\n",
    "\n",
    "Find yourself a partner at about the **same skill level**. Both of you should follow the debugger steps and write code on your own laptops, although you only need to fill out one copy of this tutorial sheet. Take turns explaining what you predict and what you observe. Write both your names below.\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "<b>ℹ️ Checking your work</b>\n",
    "\n",
    "As before, replace the placeholder in each checker cell and run it using the ▶️ button or Ctrl+Enter. Leave its <code>%%check</code> line in place. Paste only the output requested, without commands, terminal prompts, or quotation marks added around the whole answer.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 1.0.1\n",
    "WRITE NAMES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-04",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"1\" hidden></span>\n",
    "\n",
    "## 2 Getting started\n",
    "\n",
    "### 2.1 A suspicious receipt\n",
    "\n",
    "In VS Code, open your `Intro to Programming` folder. Create a folder called `tutorial-5`, then open that folder using **File > Open Folder...**. Download [buggy_cafe.py](buggy_cafe.py) and put it inside.\n",
    "\n",
    "Read the file before running it. The café's rules are:\n",
    "\n",
    "- Add all the prices to get the basket's subtotal.\n",
    "- Delivery costs **£2 below £8**, and is **free from £8 upwards**.\n",
    "- Prices are non-negative numbers. Even an empty basket has a £2 delivery charge; the café is unusually committed to making that journey.\n",
    "\n",
    "The supplied basket is `[3, 1, 4]`. Work out the subtotal and final bill together. What should the program print?\n",
    "\n",
    "Now run the file. Paste its **actual** output below. Keep the file unchanged for now, even if you can already spot a bug."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 2.1.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-06",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"2\" hidden></span>\n",
    "\n",
    "### 2.2 Pause the program\n",
    "\n",
    "The bill should have been **£8.00**, as the prices sum to £8 and that means there is no delivery charge. While Python reported no exception,  our answer is wrong, meaning that there is a **logic error** somewhere in our code. The debugger lets us inspect the running program to find its cause.\n",
    "\n",
    "1. Open the **Extensions** sidebar and check that Microsoft's **Python** and **Python Debugger** extensions are installed and enabled. The latter should have been installed when you set up Python in Tutorial 1, but install it if it is missing.\n",
    "2. In `buggy_cafe.py`, find `subtotal = basket_total(prices)` inside `receipt`. Click in the margin **to the left of its line number** to activate a **red dot**. This dot is called a **breakpoint**, a place where execution will pause for us to inspect our code.\n",
    "3. Save the file. Open the dropdown next to the editor's run button and choose **Python Debugger: Debug Python File** (sometimes labelled **Debug Python File**). Alternatively, use **Run > Start Debugging**; if prompted, select **Python Debugger**, then **Python File**. Keep `buggy_cafe.py` as the active editor tab.\n",
    "4. The program should pause with that line highlighted. If it doesn't already open automatically, open the **Run and Debug** sidebar on the left of VS Code using the play-and-bug icon. Expand **VARIABLES** at the top of the menu, then **Locals**, to inspect `prices`. Hovering over `prices` in the editor also shows its value.\n",
    "5. Open **View > Debug Console**, or, if you already had a Terminal open, select the **Debug Console** tab at the top of the Terminal window. While still paused in `receipt`, type `prices` and press Enter. Paste the displayed list below.\n",
    "\n",
    "So, what has happened here? When using debugger, the program runs as normal until it encounters a breakpoint. Then it pauses, before running the highlighted line, and the debugger interface allows us to inspect everything about our program. This can be a lot more convenient than putting in a bunch of `print()` statements, especially in more complex programs!\n",
    "\n",
    "The highlighted line is the **next line to execute**. The call to `basket_total` has not happened yet, so `subtotal` has not been assigned in this call to `receipt`.\n",
    "\n",
    "If the program runs straight through, double-check that you set the breakpoint, saved the file, and ran the file using the debugger! The ordinary run button does not stop at breakpoints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-07",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 2.2.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-08",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"3\" hidden></span>\n",
    "\n",
    "## 3 Following the execution\n",
    "\n",
    "### 3.1 Into the basket\n",
    "\n",
    "When the program paused, the debugger toolbar should have appeared at the top of your screen. It looks a bit like a row of music playback controls and you can move it around using the six dots on the left if you'd like. Hovering over each button shows you its names as well as the keyboard shortcuts associated with each command.\n",
    "\n",
    "| Control | Function |\n",
    "| --- | --- |\n",
    "| **Continue** | Continue the program until you hit the next breakpoint, an error, or the end of the program. |\n",
    "| **Step Over** | Execute the current line, (usually) completing any function calls on it without following their bodies. A breakpoint inside a call can still interrupt. |\n",
    "| **Step Into** | Follow a function call so you can inspect its execution. |\n",
    "| **Step Out** | Run the rest of the current function and pause back in its caller. Other breakpoints can still interrupt. |\n",
    "| **Restart** | Start the program again from the beginning. |\n",
    "| **Stop** | End this debugging run. |\n",
    "\n",
    "*Continue*, *Restart*, and *Stop* are mostly self-explanatory, but let's discuss the others in a bit more detail. In essense, they allow us to determine what we want to happen when a function call is highlighted by a breakpoint. There are two options:\n",
    "- You can *Step Over* the function, executing it without bothering to go through the function step-by-step (unless you set additional breakpoints inside that function); or\n",
    "- You can *Step Into* it, following the function step-by-step and returning to the caller when it's finished.\n",
    "\n",
    "If you've chosen to *Step Into* a function, but decide while going through it that you've seen enough and would like to return to the caller, you can then use the *Step Out* button to run the rest of the function, once again only stopping at breakpoints you set.\n",
    "\n",
    "Let's try it out in practice.\n",
    "\n",
    "1. With `subtotal = basket_total(prices)` still highlighted, choose **Step Into**. You should enter `basket_total`.\n",
    "2. Expand **CALL STACK** in the Run and Debug panel.\n",
    "\n",
    "Among its entries you should find `basket_total`, `receipt`, and `main`, the current function and the calls waiting for it to finish. The call stack tells you how deep in your code you are: inside the `basket_total` function, called by the `receipt` function, called by the `main` function, called by the current module. Each entry is a **stack frame**, and clicking on one highlights where in the code they occurred with its local variables.\n",
    "\n",
    "3. Select the `receipt` frame, then the `basket_total` frame. Notice that the variables shown belong to the selected call. Note that selecting a frame only changes what you inspect - it does not run the program backwards. Leave `basket_total` selected.\n",
    "4. Use **Step Over** twice, watching the highlighted line, until it reaches `total = price` for the **first** time. Do not execute that line yet. Python has initialised `total` and chosen the first `price`.\n",
    "5. In the Debug Console, evaluate `price, total`. This expression displays the two values as a tuple. Paste that tuple below.\n",
    "\n",
    "Note: the Debug Console evaluates Python in the selected frame. We are only using it to read values, but assigning to a variable or calling a method that changes a list there would also change the paused program!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-09",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.1.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-10",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"4\" hidden></span>\n",
    "\n",
    "### 3.2 Watch what changes\n",
    "\n",
    "Before continuing, let's predict the running total **after** each price has been processed. For `[3, 1, 4]`, the intended totals should be `3`, then `4`, then `8`.\n",
    "\n",
    "In the **WATCH** section of Run and Debug, use **+** to add the expression `total`. A watch expression is evaluated again whenever execution pauses, using the selected frame. If a name does not exist in that frame, its watch cannot show a value there.\n",
    "\n",
    "Now step through the loop:\n",
    "\n",
    "1. Use **Step Over** to execute `total = price` once, then record `total` from WATCH or VARIABLES.\n",
    "2. Step until `total = price` is highlighted for the second price. Predict what it will do, execute it once, and record `total` again.\n",
    "3. Repeat for the final price. Stop when `return total` is highlighted, **before executing the return**.\n",
    "\n",
    "Paste your three **observed totals**, one per line and in iteration order, below. Then discuss: on which iteration does reality first disagree with our prediction? Which statement produces that disagreement?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-11",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.2.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-12",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"5\" hidden></span>\n",
    "\n",
    "### 3.3 Back to the caller\n",
    "\n",
    "With `return total` highlighted, choose **Step Out**. You should return to `receipt`, where the result of `basket_total(prices)` is assigned to `subtotal`. Depending on your debugger version, you may need one more **Step Over** to finish the assignment. Stop with `delivery = 2` highlighted.\n",
    "\n",
    "Select `receipt` in CALL STACK and evaluate `subtotal` in the Debug Console. Paste its value below.\n",
    "\n",
    "Compare the stack with the one you saw inside the loop. The completed `basket_total` call is gone, and its local name `total`, still added to the WATCH section, is no longer available as only the returned value is passed back to the caller.\n",
    "\n",
    "Once you have recorded the value, choose **Continue** to let the program finish. The Debugger interface vanishes and the program's output appears in the **Terminal** panel. If you are still seeing the Debugger Console, switch over manually."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-13",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.3.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-14",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"6\" hidden></span>\n",
    "\n",
    "### 3.4 Repair the mistake\n",
    "\n",
    "Discuss what the loop should do with the previous total and the new price. Then change **one line** in `basket_total` so it keeps a running total. Use your observations to justify the change.\n",
    "\n",
    "At the start of `main()`, before the existing two lines, add these checks:\n",
    "\n",
    "```python\n",
    "assert basket_total([3, 1, 4]) == 8\n",
    "assert basket_total([5]) == 5\n",
    "assert basket_total([]) == 0\n",
    "```\n",
    "\n",
    "They cover several prices, one price, and no prices. Keeping relevant checks after a bug fix helps catch the same problem in the future.\n",
    "\n",
    "Save your change, then start a **new** run using **Run Python File in Terminal**.\n",
    "\n",
    "Paste the receipt now printed below. Have we fixed the code completely?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-15",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.4.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-16",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"7\" hidden></span>\n",
    "\n",
    "### 3.5 Boundary bug\n",
    "\n",
    "While our subtotal is now right, the bill is still wrong!\n",
    "\n",
    "Remove the old breakpoint by clicking its red dot. Set a new one on the `if` line inside `receipt`, save, and start **Debug Python File** again.\n",
    "\n",
    "1. Inspect `subtotal` and `delivery` before the condition runs. What should the delivery charge become for this basket?\n",
    "2. Evaluate the condition from the `if` line in the Debug Console. Does it give the Boolean you expected?\n",
    "3. Use Step Over to see whether Python enters the branch. Which comparison expresses **“from £8 upwards”**?\n",
    "4. Stop, repair the condition, and save.\n",
    "\n",
    "Replace `main()` with the version below. These receipt checks cover a subtotal just **below**, **at**, and just **above** the free-delivery boundary.\n",
    "\n",
    "```python\n",
    "def main():\n",
    "    assert basket_total([3, 1, 4]) == 8\n",
    "    assert basket_total([5]) == 5\n",
    "    assert basket_total([]) == 0\n",
    "    assert receipt([3, 1, 3]) == \"Total including delivery: £9.00\"\n",
    "    assert receipt([3, 1, 4]) == \"Total including delivery: £8.00\"\n",
    "    assert receipt([3, 1, 5]) == \"Total including delivery: £9.00\"\n",
    "\n",
    "    prices = [3, 1, 4]\n",
    "    print(receipt(prices))\n",
    "    print(\"All cafe checks passed!\")\n",
    "```\n",
    "\n",
    "Remove your breakpoints and run the file. Paste its two output lines below.\n",
    "\n",
    "We have now gone through a full investigation cycle: **reproduce → predict → pause and inspect → explain → repair → recheck**. Well done, this is how you use the debugger!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-17",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 3.5.1\n",
    "PASTE OUTPUT HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-18",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"8\" hidden></span>\n",
    "\n",
    "## 4 Bug your own tutorial\n",
    "\n",
    "### 4.1 Decide what should happen\n",
    "\n",
    "Welcome to the second half of the tutorial. Your pair will make a small debugging challenge for another pair. You'll need a working program first: otherwise you cannot be sure which behaviour you have broken!\n",
    "\n",
    "Choose something you can explain in a few sentences. For example:\n",
    "\n",
    "| Idea | A possible rule to investigate |\n",
    "| --- | --- |\n",
    "| A game scorekeeper | Add round scores and award a bonus at a chosen threshold. |\n",
    "| A study planner | Select activities that fit a time budget and report their total duration. |\n",
    "| A creature shelter | Use each creature's age and needs to decide which ones require a visit. |\n",
    "| A packing helper | Count supplies and decide whether an expedition is ready to leave. |\n",
    "\n",
    "Feel free to use your own ideas if you have any, but keep the scope small enough to leave time for the exchange.\n",
    "\n",
    "Your challenge should fit in **one `.py` file**, probably around **30–60 lines** excluding comments and checks. Include:\n",
    "\n",
    "- At least **two functions**, with one calling another, so there is a useful call stack to explore.\n",
    "- A **list or dictionary**, a **loop**, and a **condition** whose results matter to the output.\n",
    "- At least **three cases with known expected results**: an ordinary case, a boundary case, and an empty, single-item, or repeated-item case appropriate to your rules.\n",
    "\n",
    "Before coding, record your plan below: the program's purpose, its exact rules (including boundaries), the jobs of your functions, and a table of your chosen inputs and expected results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-19",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.1.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-20",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"9\" hidden></span>\n",
    "\n",
    "### 4.2 Build the healthy version\n",
    "\n",
    "Create your file. Implement one small part at a time, following your plan. If you would like a starting shape, adapt this one, but feel free use your own structure and more suitable names.\n",
    "\n",
    "```python\n",
    "def analyse_items(items, limit):\n",
    "    pass  # Apply your rules with a loop and condition, then return a result\n",
    "\n",
    "\n",
    "def make_report(items, limit):\n",
    "    result = analyse_items(items, limit)\n",
    "    return f\"Result: {result}\"\n",
    "\n",
    "\n",
    "def main():\n",
    "    items = []  # Replace this with your ordinary example\n",
    "    limit = 10  # Choose a value meaningful for your program\n",
    "    print(make_report(items, limit))\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "\n",
    "\n",
    "1. Implement the ordinary case. Run it and compare its output with your hand-worked answer.\n",
    "2. Add the other planned cases. Write at least one `assert` statement for each case, checking your functions' returned values against the expected values. Put these checks in `main()` before or after your demonstration calls.\n",
    "3. Save and run the entire file in a fresh process. All assertions must pass. If you use floating-point calculations, use `math.isclose()` where appropriate.\n",
    "4. Use a breakpoint and Step Into once to check that your function calls give another pair something useful to inspect.\n",
    "\n",
    "Keep this working file as your reference. Record each case's input, expected result, actual result, and whether its assertion passed below. If you are running short of time, simplify your program now, before introducing the bugs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-21",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.2.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-22",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"10\" hidden></span>\n",
    "\n",
    "### 4.3 Introduce three bugs\n",
    "\n",
    "Make a copy called `challenge_buggy.py`. In that copy, introduce **three deliberate bugs**. Keep your working version unchanged.\n",
    "\n",
    "At least **two** bugs should change a result while allowing Python to run: for example, a wrong boundary, an accumulator reset in the wrong place, a skipped list item, an incorrect dictionary key, or two names unexpectedly referring to the same mutable object. The third may be another logic error or an exception reached while running the program. Choose mistakes that make sense for your own idea.\n",
    "\n",
    "Avoid syntax errors, misleading function names, or deleting large sections of code. The challenge should reward using the debugger. Keep the assertions, as they are useful clues for the other team.\n",
    "\n",
    "For **each** change:\n",
    "\n",
    "1. Explain which rule it violates.\n",
    "2. Run a small example that exposes it. Record the expected and observed result or exception. If another bug hides it, investigate this change on its own in a temporary copy of the working file.\n",
    "3. Identify a breakpoint and variable that would help reveal its cause.\n",
    "4. Write two hints: first a useful input to try, then a variable or function to inspect. Keep the repair separate from the hints.\n",
    "\n",
    "Record your answers below, but don't show them to the other team!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-23",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.3.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-24",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"11\" hidden></span>\n",
    "\n",
    "### 4.4 Package the puzzle\n",
    "\n",
    "At the top of `challenge_buggy.py`, add a short **comment block or docstring** for the receiving pair. Include your challenge title and the intended behaviour, with unambiguous boundary rules.\n",
    "\n",
    "Do not mark the broken lines or include the repairs in this file, but keep your assertions and any useful comments describing what the functions are meant to do.\n",
    "\n",
    "Then, find another pair that is ready and exchange **only `challenge_buggy.py`**, using the file-sharing method your tutor recommends. If nobody is ready yet, you can get started on the bonus tasks already - the checker cells in the next section all allow any input, so add placeholders for now to advance to Section 6."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-25",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 4.4.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-26",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"12\" hidden></span>\n",
    "\n",
    "## 5 Gotta catch 'em all\n",
    "\n",
    "### 5.1 Into bug-infested waters\n",
    "\n",
    "Alright, time to fix someone else's code! Read it together, try to work out some expected input-output pairs, and then run the code. What did you expect would happen? And what actually happened?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-27",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 5.1.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-28",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"13\" hidden></span>\n",
    "\n",
    "### 5.2 Follow the evidence\n",
    "\n",
    "Use the debugger to find and repair the three bugs. For each one:\n",
    "\n",
    "1. Put a breakpoint **before** the suspicious calculation or decision, then start debugging the received file.\n",
    "2. Predict the relevant values. Step through the code and inspect VARIABLES or WATCH until you find the first disagreement. Use Step Into and CALL STACK when a function returns an unexpected result.\n",
    "3. Explain the cause to your partner before editing. Stop the run, make one repair, save, and start again.\n",
    "4. Rerun the exposing case **and all supplied checks**. A new failure can mean that an earlier bug was hiding another one!\n",
    "\n",
    "Swap who leads the investigation after each bug, so both of you practise using the controls. If stuck, request a hint from the authors.\n",
    "\n",
    "Keep a short investigation log below, with one entry per bug, for example:\n",
    "\n",
    "```text\n",
    "Input and expected result:\n",
    "Breakpoint and selected function:\n",
    "Predicted value / observed value:\n",
    "Cause and repair:\n",
    "Cases checked after the repair:\n",
    "```\n",
    "\n",
    "If time runs out, record what you established and any unresolved symptom, then work through the remaining evidence with the authors during the debrief."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-29",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 5.2.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-30",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"14\" hidden></span>\n",
    "\n",
    "### 5.3 Compare notes\n",
    "\n",
    "Reunite with the authors. Compare your investigation log with their private bug list and working version. Did you solve it in the same way or find a different solution?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-31",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 5.3.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-32",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"15\" hidden></span>\n",
    "\n",
    "## 6 Bonus Tasks\n",
    "\n",
    "Well done, that was the core part of the tutorial! Your tutor will lead a group discussion at the end. If there is still time, choose whichever task interests you most. You can do them in any order.\n",
    "\n",
    "### 6.1 Advanced bug-catching\n",
    "\n",
    "Stepping through every iteration is useful for a tiny basket. What if there are hundreds? Explore some of these advanced features using either your repaired café file or your own challenge:\n",
    "\n",
    "- **Conditional breakpoints.** Right-click in the margin and choose **Add Conditional Breakpoint** (or edit an existing breakpoint). On the café's accumulator line, try the condition `price == 4`. Predict `total` before that line executes, then inspect it when the debugger stops.\n",
    "- **Logpoints.** Right-click the margin and choose **Add Logpoint**. On that same line, try `price={price}, total before adding={total}`. Remove or disable ordinary breakpoints and run under the debugger. Look in the Debug Console for the messages. How does this compare with adding `print()` calls? Does the displayed total include the current price yet?\n",
    "- **Exception breakpoints.** In the BREAKPOINTS section, explore the options for raised and uncaught exceptions. Use a separate `exception_demo.py` containing the code below. Compare runs with **Raised Exceptions** and **Uncaught Exceptions** enabled one at a time. What changes when the exception is handled?\n",
    "\n",
    "```python\n",
    "try:\n",
    "    number = int(\"tea\")\n",
    "except ValueError:\n",
    "    print(\"That was not a number.\")\n",
    "```\n",
    "\n",
    "Use the [VS Code Python debugging guide](https://code.visualstudio.com/docs/python/debugging) and [breakpoint documentation](https://code.visualstudio.com/docs/debugtest/debugging#_breakpoints) to explore.\n",
    "\n",
    "Record the features you tried, what you predicted, what happened, and a situation where each would be useful."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-33",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 6.1.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-34",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"15\" hidden></span>\n",
    "\n",
    "### 6.2 Debugging in Noteable\n",
    "\n",
    "We have used `.py` files in VS Code, but our notebooks contain Python too. Let's explore debugging in **Noteable**.\n",
    "\n",
    "1. Create a **new Python notebook** in Noteable and look for the **bug icon** at the top right of the notebook to enable the debugger.\n",
    "2. Put this deliberately broken function in one cell and run the definition:\n",
    "\n",
    "```python\n",
    "def basket_total(prices):\n",
    "    total = 0\n",
    "    for price in prices:\n",
    "        total = price\n",
    "    return total\n",
    "```\n",
    "\n",
    "3. Set a breakpoint in that cell's line-number margin on `total = price`. In a **second cell**, run `print(basket_total([3, 1, 4]))`. Use the debugger's stepping controls, variable inspector, and call stack to reproduce the first half's observations.\n",
    "4. Stop or finish the run, fix the function, and **rerun its definition cell** before running the calling cell again. Remember that notebooks keep their existing function definitions until you execute the changed definitions.\n",
    "\n",
    "If you need help, see the [Noteable user guide](https://noteable.edina.ac.uk/user-guide/) and [JupyterLab debugger guide](https://jupyterlab.readthedocs.io/en/stable/user/debugger.html).\n",
    "\n",
    "Record one similarity and one difference compared with VS Code. Why can editing a definition without rerunning its cell make a notebook seem to ignore your repair?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-35",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 6.2.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-36",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"15\" hidden></span>\n",
    "\n",
    "### 6.3 The festival of bugs\n",
    "\n",
    "Ready for a harder investigation? Download [buggy_festival.py](buggy_festival.py), save a copy in `tutorial-5`, and open it in VS Code. The local wildlife society has organised a festival, but its scoreboard has organised a small disaster.\n",
    "\n",
    "This file contains **six deliberate faults**. Read the specification in its opening docstring and then skim to program to get a sense of how it works.\n",
    "\n",
    "The main example should produce totals of **10 for Herons, 12 for Badgers, and 10 for Owls**, in that order, with all three qualified and Badgers winning. The other two examples check a tie and an empty event. When fully repaired, the file should print:\n",
    "\n",
    "```text\n",
    "MAIN EVENT\n",
    "Herons: 10 points; qualified: True\n",
    "Badgers: 12 points; qualified: True\n",
    "Owls: 10 points; qualified: True\n",
    "Winner: Badgers\n",
    "Teams: 3\n",
    "\n",
    "TIE BREAK\n",
    "Newts: 10 points; qualified: True\n",
    "Moles: 10 points; qualified: True\n",
    "Winner: Newts\n",
    "Teams: 2\n",
    "\n",
    "EMPTY EVENT\n",
    "Winner: none\n",
    "Teams: 0\n",
    "```\n",
    "\n",
    "Start with the first exception. After each repair, stop and launch a fresh run, as later failures may have been hidden by the earlier one. Watch objects as well as individual numbers, and check whether changing one team's scores unexpectedly affects another team's scores. Make a list of the six causes as you find them.\n",
    "\n",
    "Once the three reports agree, add assertions for these extra cases in a separate `festival_checks.py` that imports your repaired file's functions.\n",
    "\n",
    "- A single valid row creates one team, including when its score is zero.\n",
    "- Non-numeric and negative scores are ignored without creating teams.\n",
    "- Names with surrounding spaces are grouped with their stripped names.\n",
    "- Updating one team leaves other teams unchanged, and building another event does not change earlier teams.\n",
    "\n",
    "Record the six causes and repairs and the extra checks you tried. If you weren't able to finish in the allocated time, record your progress and next hypothesis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "t5-37",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%check 6.3.1\n",
    "WRITE NOTES HERE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "t5-38",
   "metadata": {},
   "source": [
    "<span class=\"tutorial-section-marker\" data-tutorial-section=\"15\" hidden></span>\n",
    "\n",
    "## 7 Summary\n",
    "\n",
    "Well done, investigators! You have paused a running program, inspected its state, followed calls between functions, and used evidence to explain and repair incorrect behaviour. This concludes our multi-tutorial investigation into  common Python tooling. Only one tutorial left...\n",
    "\n",
    "Some key terms to take away:\n",
    "\n",
    "<dl>\n",
    "    <dt><b>Bug</b></dt>\n",
    "    <dd>A fault in a program. It can cause an exception, but it can also quietly produce an incorrect result.</dd>\n",
    "    <dt><b>Debugger</b></dt>\n",
    "    <dd>A tool for controlling execution and inspecting a running program's state.</dd>\n",
    "    <dt><b>Breakpoint</b></dt>\n",
    "    <dd>A marked location where the debugger pauses, normally before executing that line.</dd>\n",
    "    <dt><b>Step Over, Step Into, Step Out</b></dt>\n",
    "    <dd>Controls for executing a line, following a function call, and finishing the current call.</dd>\n",
    "    <dt><b>Call stack and frame</b></dt>\n",
    "    <dd>The active chain of function calls, and the information belonging to one particular call, including its local variables.</dd>\n",
    "    <dt><b>Watch expression</b></dt>\n",
    "    <dd>An expression evaluated when execution pauses, in the selected frame.</dd>\n",
    "    <dt><b>Regression check</b></dt>\n",
    "    <dd>A check kept after a repair to detect the same failure if a later change reintroduces it.</dd>\n",
    "</dl>\n",
    "\n",
    "### Sources and further reading\n",
    "\n",
    "- [Smithsonian: the Mark II logbook and its moth](https://americanhistory.si.edu/collections/object/nmah_334663).\n",
    "- [VS Code: Python debugging](https://code.visualstudio.com/docs/python/debugging) and [general debugger controls](https://code.visualstudio.com/docs/debugtest/debugging).\n",
    "- [Noteable: user guide](https://noteable.edina.ac.uk/user-guide/).\n",
    "- [JupyterLab: debugger](https://jupyterlab.readthedocs.io/en/stable/user/debugger.html).\n",
    "- [Python: errors and exceptions](https://docs.python.org/3/tutorial/errors.html).\n",
    "\n",
    "---\n",
    "\n",
    "### Start over\n",
    "\n",
    "Use this button to erase every answer in this notebook and begin the tutorial again. It resets notebook answers and progress; it does not change the Python files you created or repaired.\n",
    "\n",
    "<button type=\"button\" data-tutorial-reset style=\"padding:8px 14px;border:1px solid #b91c1c;border-radius:6px;background:#dc2626;color:white;font-weight:600;cursor:pointer\">Reset all tutorial progress</button>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
