{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "l13-c000",
   "metadata": {},
   "source": [
    "# Lecture 14 - Code quality 2: Community conventions\n",
    "\n",
    "**Authors:** Fiona McNeill, Matteo Degiacomi, Rayo Verweij, and Nigel Topham\n",
    "\n",
    "## Introduction\n",
    "\n",
    "We're wrapping up Part 2 of the core course content by looking at common Python conventions that will help you write better code, and in doing so, revisiting some of the fundamental concepts we've seen so far.\n",
    "\n",
    "### Learning outcomes\n",
    "\n",
    "In this notebook, we'll discuss:\n",
    "\n",
    "- Python's style conventions for variable names and constants;\n",
    "- recognising function side effects and avoiding shared mutable defaults; and\n",
    "- documenting the expected types of arguments and return values with type hints.\n",
    "\n",
    "### Using the notebook\n",
    "\n",
    "Remember, this notebook is _yours_! You can edit each cell, for example by adding new examples or changing values to see what happens. Feel free to experiment!\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "A common approach for learning how to read and write code in a structured way is called **PRIMM**:\n",
    "1. **Predict**: before running the code, look at it - do you understand each line? What do you think will happen?\n",
    "2. **Run**: now run the code and see what output you get.\n",
    "3. **Investigate**: did it go as you thought it would? If not, can you figure out why?\n",
    "4. **Modify**: now change the code and once again try to predict the output. If you got it wrong the first time, did you get it right now?\n",
    "5. **Make**: finally, try to write your own program from scratch using the skills you learned.\n",
    "\n",
    "You can apply steps 1-4 to each code cell in the notebook and many will have prediction prompts to help you get started. In addition, there will be challenges that ask you to put everything together yourself and execute step 5. There will often be multiple ways to solve these, but each challenge has a potential answer listed.\n",
    "\n",
    "</details>\n",
    "\n",
    "### Navigating the notebook\n",
    "\n",
    "A Jupyter notebook can be operated with your keyboard. Here is a **cheat sheet**:\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "- To run the selected cell and move to the next cell, press <kbd>&#x21E7; Shift</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To run the selected cell and keep focus there, press <kbd>⌃ Ctrl</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To create a cell under the one currently highlighted, press <kbd>B</kbd>;\n",
    "- To delete the currently highlighted cell, press <kbd>D</kbd> twice (be careful with this one!) or press <kbd>X</kbd> to cut it;\n",
    "- To get help for a specific function, place the cursor within the function's brackets, hold <kbd>&#x21E7; Shift</kbd>, and press <kbd>&#x21E5; Tab</kbd>.\n",
    "\n",
    "</details>\n",
    "\n",
    "Watch out: **code cells remember what happened in cells before**. So, especially in the more complicated notebooks later down the line, make sure to always run **every** cell from top to bottom, as one might rely on a piece of code that came before it! If your results become confusing, use **Kernel > Restart Kernel** and then rerun all the completed cells in order.\n",
    "\n",
    "### Further reading and practice\n",
    "\n",
    "- Python Enhancement Proposals: some relevant ones include [PEP 1 - PEP Purpose and Guidelines](https://peps.python.org/pep-0001/), [PEP 8 - Style Guide for Python Code](https://peps.python.org/pep-0008/), [PEP 20 - The Zen of Python](https://peps.python.org/pep-0020/), and [PEP 257 - Docstring Conventions](https://peps.python.org/pep-0257/).\n",
    "- Official Python tutorial: [Function annotations](https://docs.python.org/3/tutorial/controlflow.html#function-annotations) and [Default argument values](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values).\n",
    "- W3Schools: no relevant pages this time!\n",
    "- Helsinki Python MOOC: [The type of the argument](https://programming-26.mooc.fi/part-4/2-more-functions#the-type-of-the-argument)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e25bb93",
   "metadata": {},
   "source": [
    "## 1. Python's style guide"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ccb35474",
   "metadata": {},
   "source": [
    "Before we start, run the following program. No, nothing is missing!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4fda00f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Zen of Python, by Tim Peters\n",
      "\n",
      "Beautiful is better than ugly.\n",
      "Explicit is better than implicit.\n",
      "Simple is better than complex.\n",
      "Complex is better than complicated.\n",
      "Flat is better than nested.\n",
      "Sparse is better than dense.\n",
      "Readability counts.\n",
      "Special cases aren't special enough to break the rules.\n",
      "Although practicality beats purity.\n",
      "Errors should never pass silently.\n",
      "Unless explicitly silenced.\n",
      "In the face of ambiguity, refuse the temptation to guess.\n",
      "There should be one-- and preferably only one --obvious way to do it.\n",
      "Although that way may not be obvious at first unless you're Dutch.\n",
      "Now is better than never.\n",
      "Although never is often better than *right* now.\n",
      "If the implementation is hard to explain, it's a bad idea.\n",
      "If the implementation is easy to explain, it may be a good idea.\n",
      "Namespaces are one honking great idea -- let's do more of those!\n"
     ]
    }
   ],
   "source": [
    "import this"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee0997ef",
   "metadata": {},
   "source": [
    "Congratulations, you've found one of Python's **easter eggs**! This is [PEP 20 - The Zen of Python](https://peps.python.org/pep-0020/), an overview of the guiding principles behind Python's design.\n",
    "\n",
    "PEP stands for [Python Enhancement Proposal](https://peps.python.org/) and is the main way in which the Python community proposes new features for the language. For example, [PEP 285](https://peps.python.org/pep-0285/) added the `bool` type, which did not exist before Python 2.3 - before then, Python developers had to use the integers 0 and 1 as placeholders!\n",
    "\n",
    "PEP 20 is a lovely starting point but not particularly practical when using it as a guide to write code. Thankfully, we have [PEP 8](https://peps.python.org/pep-0008/), the official Style Guide for Python code.\n",
    "\n",
    "We've already used a lot of PEP 8 conventions so far, such as\n",
    "- `lowercase_with_underscores` for variable and function names;\n",
    "- `CapWords` for class names;\n",
    "- four spaces per indentation level; and\n",
    "- capping lines to at most 79 characters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a6ff5e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CamelCase:\n",
    "    \"\"\"Very long lines should be avoided where possible and broken up after 79\n",
    "    characters\"\"\"\n",
    "    lower_case = \"a class attribute\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0b92ba4",
   "metadata": {},
   "source": [
    "Note: these are style conventions and not hard rules. Your code will not break if your lines are longer than 79 characters and Python will not throw an error when you use tabs instead of spaces to indent (unless you mix tabs *and* spaces, which is not allowed). What is considered good style often differs between programming languages and you do not always have to follow the rules to the letter - in fact, as PEP 8 says, quoting the essay *Self-Reliance* (1841) by Ralph Waldo Emerson, *A Foolish Consistency is the Hobgoblin of Little Minds*.\n",
    "\n",
    "Most importantly, keep your code **readable** and **consistent**. As PEP 8 stresses, code is *read* much more often than it is *written* - often by the person who wrote it in the first place, trying to figure out what they had written in the first place!\n",
    "\n",
    "It is still important, however, to be aware of the most commonly used conventions in the Python community, as many of these will make your life easier, lead to better code, and are often even integrated in code editors such as Noteable or VS Code. This notebook discusses a few of the highlights and, in doing so, revises some of the core concepts we have seen in the course so far."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12d6d48f",
   "metadata": {},
   "source": [
    "## 2. Constants"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c007",
   "metadata": {},
   "source": [
    "When writing programs, you often have values that don't change and are simply true for the entire program. A **constant** is a value you intend to keep unchanged while the program runs.\n",
    "\n",
    "Some programming languages actually make you _specify_ whether you can reassign variables or not. Python does not do this - every name can be reassigned. However, to make it clear which names we don't intend to reassign, it's a convention to write constants in capital letters.\n",
    "\n",
    "Constants are often kept together at the very beginning of code, just after your imports, so they can be easily found and changed when necessary.\n",
    "\n",
    "**Predict:** If the shop changed its threshold to £100, which line would we change?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c008",
   "metadata": {},
   "outputs": [],
   "source": [
    "DISCOUNT_THRESHOLD = 50\n",
    "DISCOUNT_RATE = 0.10\n",
    "\n",
    "def apply_discount(total):\n",
    "    if total >= DISCOUNT_THRESHOLD:\n",
    "        return total * (1 - DISCOUNT_RATE)\n",
    "    return total\n",
    "\n",
    "print(apply_discount(60))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8490426",
   "metadata": {},
   "source": [
    "## 3. Pure functions and side-effects"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c016",
   "metadata": {},
   "source": [
    "A function is **pure** if:\n",
    "\n",
    "- its result depends only on its arguments, so calling it again with the same arguments gives the same result, and\n",
    "- it has no side effects: it changes nothing outside itself.\n",
    "\n",
    "A function that breaks either rule is **impure**. The calculation below is pure, as the `print()` calls outside it display the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c017",
   "metadata": {},
   "outputs": [],
   "source": [
    "def pure_total(price, quantity):\n",
    "    return price * quantity\n",
    "\n",
    "print(pure_total(2.5, 3))\n",
    "print(pure_total(2.5, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-impure-01",
   "metadata": {},
   "source": [
    "The next function breaks the first rule. `with_tax()` reads `tax_rate`, a variable defined outside the function, rather than receiving it as an argument. Note the lowercase name: `tax_rate` is not a constant, and here it changes.\n",
    "\n",
    "**Predict:** We call `with_tax(10)` twice. Do we get the same result?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l14-impure-02",
   "metadata": {},
   "outputs": [],
   "source": [
    "tax_rate = 0.2\n",
    "\n",
    "def with_tax(price):\n",
    "    return price * (1 + tax_rate)\n",
    "\n",
    "print(with_tax(10))\n",
    "tax_rate = 0.25\n",
    "print(with_tax(10))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l14-impure-03",
   "metadata": {},
   "source": [
    "The same argument gives `12.0` and then `12.5`, so `with_tax()` is impure. Calling `input()` or reading the current time inside a function makes it impure in the same way, as its result no longer depends only on its arguments."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c018",
   "metadata": {},
   "source": [
    "A function has a **side effect** when it makes a change beyond the returned value, such as printing, writing a file, or changing a mutable object supplied by the caller. A function with side effects is impure, even if its result depends only on its arguments.\n",
    "\n",
    "Pure functions are not necessarily *better* than those with side-effects; in fact, most code will require some impure functions to work. However, side-effects are not always immediately visible, so the takeaway here is that **side-effects should be properly documented**.\n",
    "\n",
    "In the next example, `add_task()` changes the caller's list, so it is impure, while `with_task()` returns a new list instead and is pure. Both designs have their own use cases, but the function's name and documentation need to tell the caller what to expect.\n",
    "\n",
    "**Predict:** Which lists contain `\"practise\"` after the two calls? How would you write the docstrings for each function?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c019",
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_task(task_list, task):\n",
    "    task_list.append(task)\n",
    "\n",
    "def with_task(task_list, task):\n",
    "    updated = task_list.copy()\n",
    "    updated.append(task)\n",
    "    return updated\n",
    "\n",
    "original = [\"read\"]\n",
    "result = with_task(original, \"practise\")\n",
    "print(original, result)\n",
    "add_task(original, \"practise\")\n",
    "print(original, result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c020",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: separate a calculation from its output</b>\n",
    "\n",
    "Refactor `calculate_and_show_mean()` into `mean(numbers)`, which returns a number, and `show_mean(numbers)`, which prints the formatted result. Also add a docstring saying that `mean()` requires a non-empty list.\n",
    "\n",
    "Test (with `assert`) a one-item list as well as several values.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c021",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def calculate_and_show_mean(numbers):\n",
    "    result = sum(numbers) / len(numbers)\n",
    "    print(f\"Mean: {result:.1f}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c022",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "def mean(numbers):\n",
    "    \"\"\"Return the mean of a non-empty list of numbers.\"\"\"\n",
    "    return sum(numbers) / len(numbers)\n",
    "\n",
    "def show_mean(numbers):\n",
    "    print(f\"Mean: {mean(numbers):.1f}\")\n",
    "\n",
    "assert mean([4]) == 4\n",
    "assert mean([2, 4, 6]) == 4\n",
    "show_mean([2, 4, 6])\n",
    "```\n",
    "\n",
    "`mean()` is pure, so it is easy to test. `show_mean()` is impure: it prints.\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "417ca538",
   "metadata": {},
   "source": [
    "### Default mutable values"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c023",
   "metadata": {},
   "source": [
    "In Lecture 6, we used default parameter values such as `currency=\"£\"`. So far we have only used immutable values for our defaults, as using mutable collections causes a side-effect that is not always immediately obvious.\n",
    "\n",
    "When a default value is set, Python creates it when it executes the `def` statement, rather than creating a fresh default every time the function is called. This means that if the value is mutable, it is *shared between multiple calls of the function!*\n",
    "\n",
    "**Predict:** Will `first` and `second` refer to equal lists, the same list, or different lists?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c024",
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_label(label, labels=[]):\n",
    "    labels.append(label)\n",
    "    return labels\n",
    "\n",
    "first = add_label(\"first\")\n",
    "second = add_label(\"second\")\n",
    "print(first)\n",
    "print(second)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c025",
   "metadata": {},
   "source": [
    "Both variables refer to the same list and appending `\"second\"` changed what we see through `first` too. This is the same aliasing problem we saw in our initial discussion of collections in Lecture 5.\n",
    "\n",
    "If you don't want this behaviour, you can use `None` as a default value to mean \"no list supplied\" and then create a new list inside the function. If the caller does supply a list, it simply uses that one.\n",
    "\n",
    "To check for `None`, PEP 8 recommends `is None` rather than `== None`. `is` checks whether two names refer to the very same object, and there is only one `None`. We will look at `is` more closely in Lecture 17.\n",
    "\n",
    "**Predict:** What do the first two calls print now? What happens to `existing` in the third call?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c026",
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_label(label, labels=None):\n",
    "    \"\"\"Append to the supplied list, or create a new list if omitted.\"\"\"\n",
    "    if labels is None:\n",
    "        labels = []\n",
    "    labels.append(label)\n",
    "    return labels\n",
    "\n",
    "print(add_label(\"first\"))\n",
    "print(add_label(\"second\"))\n",
    "\n",
    "existing = [\"existing\"]\n",
    "print(add_label(\"extra\", labels=existing))\n",
    "print(existing)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c027",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: the same trap with a dictionary</b>\n",
    "\n",
    "The function `count_word()` in the cell below counts how many times each word has been seen, and it uses an empty dictionary as its default. Predict what `count_word(\"cat\")` and then `count_word(\"dog\")` return, then call them to check.\n",
    "\n",
    "Fix `count_word()` using the `None` pattern, and assert that the two calls are now independent.\n",
    "\n",
    "Finally, explain why replacing `if counts is None:` with `if not counts:` would change the behaviour when the caller supplies an empty dictionary.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c028",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def count_word(word, counts={}):\n",
    "    if word not in counts:\n",
    "        counts[word] = 0\n",
    "    counts[word] += 1\n",
    "    return counts\n",
    "\n",
    "# predict what count_word(\"cat\") and then count_word(\"dog\") return, then call them to check\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c029",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "Before the fix, the two calls return `{'cat': 1}` and then `{'cat': 1, 'dog': 1}`: the default dictionary is shared between calls, just like the default list of `add_label()`.\n",
    "\n",
    "`if not counts:` is also true for an empty dictionary, as empty collections count as `False`. It would replace the caller's empty dictionary with a new one, so the caller's dictionary would stay empty and the last assertion below would fail.\n",
    "\n",
    "```python\n",
    "def count_word(word, counts=None):\n",
    "    if counts is None:\n",
    "        counts = {}\n",
    "    if word not in counts:\n",
    "        counts[word] = 0\n",
    "    counts[word] += 1\n",
    "    return counts\n",
    "\n",
    "assert count_word(\"cat\") == {\"cat\": 1}\n",
    "assert count_word(\"dog\") == {\"dog\": 1}\n",
    "\n",
    "supplied = {}\n",
    "count_word(\"cat\", counts=supplied)\n",
    "assert supplied == {\"cat\": 1}\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bc390e4",
   "metadata": {},
   "source": [
    "## 4. Type hints"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c030",
   "metadata": {},
   "source": [
    "A **type hint**, also called a **type annotation**, tells readers and programming tools which kinds of values a function expects.\n",
    "\n",
    "Write a colon and a type after a parameter name, and `->` followed by a type before the final colon for the function's result, as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f5dc810",
   "metadata": {},
   "outputs": [],
   "source": [
    "def double(n: int) -> int:\n",
    "    return n * 2\n",
    "\n",
    "print(double(2))\n",
    "print(double(\"ha\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "158d4d0b",
   "metadata": {},
   "source": [
    "Note: as with the style guide before, this is actually just a convention. Unlike other programming languages, Python does **not** actually check or convert arguments to the types listed. Running the second function call in the above code still works, despite it providing the wrong type. However, as type hints are a very widely used feature, many code editors will pick up your type hints and highlight when the wrong type is given to a function to aid you in your writing.\n",
    "\n",
    "Using type hints is recommended for your functions, as editors and type-checking tools can use them to spot some type-related mistakes before you run the program.\n",
    "\n",
    "Collections can be described in terms of their contents. For example, `list[float]` means a list of floating-point numbers, and `dict[str, str]` means a dictionary with string keys and string values. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c031",
   "metadata": {},
   "outputs": [],
   "source": [
    "def mean(numbers: list[float]) -> float:\n",
    "    \"\"\"Return the arithmetic mean of a non-empty list.\"\"\"\n",
    "    return sum(numbers) / len(numbers)\n",
    "\n",
    "print(mean([1.0, 2.5, 4.0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97018a8e",
   "metadata": {},
   "source": [
    "When multiple types are allowed, you can use the `|` character to separate them. `|` can be read as *or*, and was a relatively recent addition, as its use in type hints was only introduced with Python 3.10 in 2021.\n",
    "\n",
    "**Predict:** Why does the following function return `str | None`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "aa9d0567",
   "metadata": {},
   "outputs": [],
   "source": [
    "def find_room(code: str, rooms: dict[str, str]) -> str | None:\n",
    "    if code in rooms:\n",
    "        return rooms[code]\n",
    "    return None\n",
    "\n",
    "print(find_room(\"IP\", {\"IP\": \"G.07\"}))\n",
    "print(find_room(\"CriSP\", {\"IP\": \"G.07\"}))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c032",
   "metadata": {},
   "source": [
    "Hints can't describe *every* condition a function might have. For example, `list[float]` in `mean()` above doesn't specify that the list must be non-empty. That information belongs in the docstring and, where appropriate, an input check. The expected inputs, results, and side-effects of a function are called its **contract** and can be specified through a combination of type hints and the docstring. The term comes from *Design by Contract*, introduced by Bertrand Meyer with his programming language Eiffel. Some languages let you write contracts directly in the code. In Python, they live in docstrings, type hints and checks."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c033",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: annotate a function</b>\n",
    "\n",
    "Write `clamp(value, lower=0.0, upper=1.0)` with `float` hints for its parameters and return value. Return the nearest bound if the value is outside the interval, or the value itself if it is inside. Document that `lower` must not be greater than `upper`.\n",
    "\n",
    "Extra: using `assert`, test its behaviour for input values below, at, inside, and above the bounds.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-c034",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# Your code here!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-c035",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "def clamp(value: float, lower: float = 0.0, upper: float = 1.0) -> float:\n",
    "    \"\"\"Limit value to the inclusive bounds. Requires lower <= upper.\"\"\"\n",
    "    if value < lower:\n",
    "        return lower\n",
    "    if value > upper:\n",
    "        return upper\n",
    "    return value\n",
    "\n",
    "assert clamp(-0.1) == 0.0\n",
    "assert clamp(0.0) == 0.0\n",
    "assert clamp(0.5) == 0.5\n",
    "assert clamp(1.0) == 1.0\n",
    "assert clamp(1.1) == 1.0\n",
    "assert clamp(25.0, lower=10.0, upper=20.0) == 20.0\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-consolidation-prompt",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "## Consolidation challenge\n",
    "\n",
    "One last challenge to wrap things up.\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: refactor a receipt</b>\n",
    "\n",
    "The cell below prints a basket total with 20% tax. Refactor it into four functions:\n",
    "\n",
    "- `line_total(price, quantity)` to calculate the cost of one line;\n",
    "- `basket_total(lines, tax_rate)` to add the line totals and apply tax;\n",
    "- `format_money(amount, currency=\"£\")` to return a string; and\n",
    "- `print_receipt(lines)` to display the same message as the original script.\n",
    "\n",
    "Use a named constant for the tax rate, and give the parameters and return values of each function type hints. Look closely at which types are nested inside one another as part of `lines`!\n",
    "\n",
    "Test each calculation separately and remember to test edge cases, such as including an empty basket. Then run the receipt function and compare its message with what you got when running the original program.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l13-consolidation-work",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "lines = [(2.5, 3), (4.0, 1)]\n",
    "subtotal = 0\n",
    "for price, quantity in lines:\n",
    "    subtotal += price * quantity\n",
    "total = subtotal * 1.20\n",
    "print(f\"Total including tax: £{total:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-consolidation-solution",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "Each line is a `(price, quantity)` tuple. `tuple[float, int]` describes its two positions, and `list[tuple[float, int]]` describes a list of those tuples.\n",
    "\n",
    "Remember that functions without a return statement still return `None`, so the type hint `-> None` describes a function with no result to use.\n",
    "\n",
    "```python\n",
    "TAX_RATE = 0.20\n",
    "\n",
    "def line_total(price: float, quantity: int) -> float:\n",
    "    return price * quantity\n",
    "\n",
    "def basket_total(lines: list[tuple[float, int]], tax_rate: float) -> float:\n",
    "    subtotal = 0.0\n",
    "    for price, quantity in lines:\n",
    "        subtotal += line_total(price, quantity)\n",
    "    return subtotal * (1 + tax_rate)\n",
    "\n",
    "def format_money(amount: float, currency: str = \"£\") -> str:\n",
    "    return f\"{currency}{amount:.2f}\"\n",
    "\n",
    "def print_receipt(lines: list[tuple[float, int]]) -> None:\n",
    "    total = basket_total(lines, TAX_RATE)\n",
    "    print(f\"Total including tax: {format_money(total)}\")\n",
    "\n",
    "\n",
    "assert line_total(2.5, 3) == 7.5\n",
    "assert line_total(2.5, 0) == 0\n",
    "\n",
    "assert basket_total([], TAX_RATE) == 0\n",
    "assert basket_total([(10.0, 1)], TAX_RATE) == 12.0\n",
    "\n",
    "assert format_money(13.8) == \"£13.80\"\n",
    "\n",
    "print_receipt(lines)\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l13-consolidation-summary",
   "metadata": {
    "tags": [
     "summary"
    ]
   },
   "source": [
    "## Summary\n",
    "\n",
    "Well done, that's all the core content of Part 2 of the course! Now that we have a good sense of the conventions of the Python community, it's time to take a look at what other programming languages do, and get a sense of what is similar and what is different.\n",
    "\n",
    "### Key terms\n",
    "\n",
    "<dl>\n",
    "\t<dt><b>Constant</b></dt>\n",
    "\t<dd>A named value intended to remain unchanged. In Python, constants aren't checked, but conventionally written with capital letters.</dd>\n",
    "\t<dt><b>Pure function</b></dt>\n",
    "\t<dd>A function whose result depends only on its arguments and which has no side effects.</dd>\n",
    "\t<dt><b>Impure function</b></dt>\n",
    "\t<dd>A function whose result depends on something other than its arguments, or which has side effects.</dd>\n",
    "\t<dt><b>Side effect</b></dt>\n",
    "\t<dd>A change beyond a returned value, such as output or mutation of a supplied object.</dd>\n",
    "\t<dt><b>Mutable default</b></dt>\n",
    "\t<dd>A changeable object used as a default parameter value. Python creates it once, when the function is defined, so every call that omits the argument shares it, and changes persist between calls.</dd>\n",
    "\t<dt><b>Function contract</b></dt>\n",
    "\t<dd>The expected inputs, results, and other behaviour of a function.</dd>\n",
    "\t<dt><b>Type hint</b> / <b>Type annotation</b></dt>\n",
    "\t<dd>Documentation in the code of expected types. Not automatically enforced by Python.</dd>\n",
    "</dl>\n",
    "\n",
    "### New syntax\n",
    "\n",
    "<dl>\n",
    "\t<dt><code>CONSTANT = 1</code></dt>\n",
    "\t<dd>An uppercase name marks a constant by convention.</dd>\n",
    "\t<dt><code>def function(argument: type) -&gt; type:</code></dt>\n",
    "\t<dd>Annotates a parameter and a return value with their expected types.</dd>\n",
    "\t<dt><code>list[type]</code>, <code>dict[type, type]</code>, <code>tuple[type, type]</code></dt>\n",
    "\t<dd>Describes the contents of collections in type hints.</dd>\n",
    "\t<dt><code>type1 | type2</code></dt>\n",
    "\t<dd>A type hint allowing multiple possible types (Python 3.10 and later).</dd>\n",
    "\t<dt><code>-&gt; None</code></dt>\n",
    "\t<dd>Documents that a function has no result for the caller to use.</dd>\n",
    "</dl>\n"
   ]
  }
 ],
 "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.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
