{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6a4bfe62",
   "metadata": {},
   "source": [
    "# Common Patterns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7516fa7",
   "metadata": {
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent\n",
    "        break\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3800096f",
   "metadata": {},
   "source": [
    "Some Python patterns appear in almost every program you will read, long before you are ready to write them. This section shows seven of them. You do not need to master them now. Read each one aloud, run it, and notice its shape. Each pattern is taught in detail in a later chapter, named in its subsection."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3da2fa62",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 1\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ead523e",
   "metadata": {},
   "source": [
    "```{index} context manager, with statement\n",
    "```\n",
    "\n",
    "## Context Managers\n",
    "\n",
    "A **context manager** sets something up, lets you use it, and cleans up afterward, even if an error occurs. The `with` statement runs one. Files are the most common case: `with open(...) as f:` closes the file as soon as the indented block ends. Read it as \"with this file open, do the following.\" Chapter 8 reads files this way, and Chapter 10 explains context managers and shows how to write your own.\n",
    "\n",
    "**Syntax (a pattern, not runnable code):**\n",
    "\n",
    "```python\n",
    "with expression as name:\n",
    "    block that uses name\n",
    "\n",
    "open(path, mode)          # a common expression to use after \"with\"\n",
    "```\n",
    "\n",
    "`expression` creates the context manager, and `name` holds what it hands back; for a file, that is the open file. The indented block runs while the resource is in use, and the cleanup runs when the block ends. For `open()`, `path` is the file's location and `mode` is `\"r\"` to read (the default), `\"w\"` to write, or `\"a\"` to append.\n",
    "\n",
    "The example stores its file in the book's `data` folder. The setup cell at the top of the notebook provides `project_root`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14df67a2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "apples\n",
      "bananas"
     ]
    }
   ],
   "source": [
    "data_dir = project_root / \"data\"\n",
    "data_dir.mkdir(parents=True, exist_ok=True)\n",
    "notes_file = data_dir / \"notes.txt\"\n",
    "\n",
    "with open(notes_file, \"w\") as f:      # \"w\" means write\n",
    "    f.write(\"apples\\nbananas\\n\")\n",
    "\n",
    "with open(notes_file) as f:           # the default mode is read\n",
    "    print(f.read())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe9be108",
   "metadata": {},
   "source": [
    "```{index} list comprehension\n",
    "```\n",
    "\n",
    "## List Comprehensions\n",
    "\n",
    "A **list comprehension** builds a new list from an existing one. Read `[p * 2 for p in prices]` as \"p times 2, for each p in prices.\" Adding an `if` at the end keeps only the items that pass the test. Chapter 6 covers comprehensions.\n",
    "\n",
    "**Syntax (a pattern, not runnable code):**\n",
    "\n",
    "```python\n",
    "[expression for item in iterable]\n",
    "[expression for item in iterable if condition]\n",
    "```\n",
    "\n",
    "`iterable` is anything you can loop over, such as a list, a string, or a `range`. Python takes each `item` in turn, and `expression` (usually built from `item`) becomes one element of the new list. With `if`, only the items for which `condition` is true are kept. The original sequence is not changed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf82804a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2.5, 1.0, 5.5, 6.2, 1.78]\n",
      "[0.5, 0.89]"
     ]
    }
   ],
   "source": [
    "prices = [1.25, 0.5, 2.75, 3.1, 0.89]\n",
    "print([p * 2 for p in prices])\n",
    "print([p for p in prices if p < 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f6fe82b",
   "metadata": {},
   "source": [
    "```{index} lambda expression\n",
    "```\n",
    "\n",
    "## Lambda Expressions\n",
    "\n",
    "A **lambda expression** is a function with no name, written on one line. Read `lambda name: len(name)` as \"given name, return its length.\" A lambda is most often passed as the `key` argument that tells `sorted()` what to sort by. Chapter 4 covers functions and lambdas.\n",
    "\n",
    "**Syntax (a pattern, not runnable code):**\n",
    "\n",
    "```python\n",
    "lambda parameters: expression\n",
    "```\n",
    "\n",
    "`parameters` are the inputs, separated by commas if there is more than one (`lambda a, b: a + b`). `expression` is the single value the function returns; there is no `return` keyword, and the body cannot hold more than one expression. It does the same job as a `def` function whose body is one `return` line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9afcc844",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['fig', 'kiwi', 'apple', 'mango', 'banana']"
     ]
    }
   ],
   "source": [
    "fruits = [\"apple\", \"banana\", \"cherry\", \"durian\", \"elderberry\"]\n",
    "print(sorted(fruits, key=lambda name: len(name)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c89ab0b7",
   "metadata": {},
   "source": [
    "```{index} conditional expression\n",
    "```\n",
    "\n",
    "## Conditional Expressions\n",
    "\n",
    "A **conditional expression** picks one of two values. Read `\"pass\" if score >= 60 else \"fail\"` as \"pass, if the score is at least 60; otherwise fail.\" Chapter 3 covers conditionals.\n",
    "\n",
    "**Syntax (a pattern, not runnable code):**\n",
    "\n",
    "```python\n",
    "value_if_true if condition else value_if_false\n",
    "```\n",
    "\n",
    "Python evaluates `condition` first. If it is true, the whole expression has the value `value_if_true`; otherwise it has the value `value_if_false`. Because it produces a value, you can assign it to a variable or use it inside `print()` or an f-string, which an `if` statement cannot do."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8016c84b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pass"
     ]
    }
   ],
   "source": [
    "score = 83\n",
    "print(\"pass\" if score >= 60 else \"fail\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad13700c",
   "metadata": {},
   "source": [
    "```{index} unpacking and expansion\n",
    "```\n",
    "## Unpacking and Expansion\n",
    "\n",
    "### Unpacking\n",
    "**Unpacking** takes an iterable apart and assigns its items to several variables in one statement:\n",
    "\n",
    "```python\n",
    "x, y = (3, 4)        # x = 3, y = 4\n",
    "```\n",
    "\n",
    "Python pulls the items one at a time, so unpacking works with any iterable (lists, tuples, strings, ranges, sets, generators), not only tuples. There are two kinds:\n",
    "\n",
    "- **Plain unpacking** assigns items to variables by position. The number of variables must equal the number of items, or Python raises a `ValueError`.\n",
    "- **Starred unpacking** puts `*` in front of one variable, which collects all leftover items into a **list**. The list may be empty, and only one starred variable is allowed per assignment.\n",
    "\n",
    "```python\n",
    "a, b, c = [10, 20, 30]           # a = 10, b = 20, c = 30\n",
    "a, b = b, a                      # swap: a = 20, b = 10\n",
    "first, *rest = [1, 2, 3, 4]      # first = 1, rest = [2, 3, 4]\n",
    "head, *mid, tail = \"python\"      # head = 'p', mid = ['y', 't', 'h', 'o'], tail = 'n'\n",
    "a, *b = [1]                      # a = 1, b = []\n",
    "a, b = [1, 2, 3]                 # ValueError: too many values to unpack\n",
    "```\n",
    "\n",
    "### Expansion\n",
    "\n",
    "**Expansion** works in the opposite direction: instead of collecting items into a variable, `*` and `**` spread items out into a new collection or a function call.\n",
    "\n",
    "- **Iterable expansion (`*`)** spreads the items of any iterable into a list, tuple, or set literal, or into the positional arguments of a function call. You can use several `*` in one expression.\n",
    "- **Dictionary expansion (`**`)** spreads a dictionary's key-value pairs into a dictionary literal or into the keyword arguments of a function call.\n",
    "\n",
    "```python\n",
    "a, b = [1, 2], (3, 4)\n",
    "[*a, *b]                         # [1, 2, 3, 4]  (works even though a and b are different types)\n",
    "print(*\"abc\")                    # a b c\n",
    "\n",
    "defaults = {\"color\": \"red\", \"size\": 1}\n",
    "user     = {\"size\": 3}\n",
    "{**defaults, **user}             # {'color': 'red', 'size': 3}\n",
    "\n",
    "def area(width, height):\n",
    "    return width * height\n",
    "\n",
    "dims = {\"width\": 4, \"height\": 5}\n",
    "area(**dims)                     # same as area(width=4, height=5) → 20\n",
    "area(**dims, width=2)            # TypeError: got multiple values for argument 'width'\n",
    "```\n",
    "\n",
    "> **Tip:** On the left side of `=`, `*` *collects* items into a list. On the right side or in a function call, `*` *spreads* items out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a89dea87",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3 4\n",
      "3 2\n",
      "apple\n",
      "['banana', 'mango', 'kiwi', 'fig']"
     ]
    }
   ],
   "source": [
    "point = (3, 4)\n",
    "x, y = point\n",
    "print(x, y)\n",
    "\n",
    "quotient, remainder = divmod(17, 5)\n",
    "print(quotient, remainder)\n",
    "\n",
    "fruits = [ \"apple\", \"banana\", \"cherry\", \"durian\" ]\n",
    "first, *others = fruits\n",
    "print(first)\n",
    "print(others)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6535f483",
   "metadata": {},
   "source": [
    "```{index} enumerate(), zip()\n",
    "```\n",
    "\n",
    "## `enumerate()` and `zip()`\n",
    "\n",
    "`enumerate()` pairs each item with its position, and `zip()` walks two sequences together. Both usually appear on a `for` line, which repeats the indented block once per item. Chapter 3 covers `for` loops.\n",
    "\n",
    "**Syntax (a pattern, not runnable code):**\n",
    "\n",
    "```python\n",
    "for item in iterable:\n",
    "    block\n",
    "\n",
    "for index, item in enumerate(iterable, start=0):\n",
    "    block\n",
    "\n",
    "for item1, item2 in zip(iterable1, iterable2):\n",
    "    block\n",
    "```\n",
    "\n",
    "A plain `for` loop sets `item` to each element of `iterable` in turn. `enumerate()` produces `(index, item)` pairs, and `start` sets the first number (the default is 0). `zip()` produces pairs of items taken from the same position in each iterable, and it stops when the shorter one runs out. Writing two names, `index, item`, unpacks each pair into two variables, as in the previous subsection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fc2c8b50",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 apple\n",
      "2 banana\n",
      "3 mango\n",
      "4 kiwi\n",
      "5 fig\n",
      "apple: $1.25\n",
      "banana: $0.50\n",
      "mango: $2.75\n",
      "kiwi: $3.10\n",
      "fig: $0.89"
     ]
    }
   ],
   "source": [
    "for i, name in enumerate(fruits, start=1):\n",
    "    print(i, name)\n",
    "\n",
    "for name, price in zip(fruits, prices):\n",
    "    print(f\"{name}: ${price:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9155154f",
   "metadata": {},
   "source": [
    "```{index} exception handling, try statement\n",
    "```\n",
    "\n",
    "## Exception Handling\n",
    "\n",
    "An error that stops a program is an **exception**. A `try` statement lets the program recover instead. Read it as \"try this; if it fails this way, do that.\" Chapter 5 covers exceptions.\n",
    "\n",
    "**Syntax (a pattern, not runnable code):**\n",
    "\n",
    "```python\n",
    "try:\n",
    "    block that might fail\n",
    "except ExceptionType:\n",
    "    block that runs if it fails that way\n",
    "```\n",
    "\n",
    "Python runs the `try` block. If it raises an exception of type `ExceptionType`, such as `ValueError` for a bad conversion, Python skips the rest of the `try` block and runs the `except` block instead. If nothing goes wrong, the `except` block is skipped. A `try` statement can also have `else` and `finally` blocks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9f7cae2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0"
     ]
    }
   ],
   "source": [
    "text = \"12a\"\n",
    "try:\n",
    "    quantity = int(text)\n",
    "except ValueError:\n",
    "    quantity = 0\n",
    "print(quantity)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7ad481e2",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Read and predict\n",
    "# Read the four patterns below without running them.\n",
    "# Fill in each predicted_ variable with the value the pattern produces.\n",
    "# Then run the cell. Each line prints True when your prediction is right.\n",
    "prices = [1.25, 0.5, 2.75, 3.1, 0.89]\n",
    "fruits = [\"apple\", \"banana\", \"mango\", \"kiwi\", \"fig\"]\n",
    "text = \"12a\"\n",
    "\n",
    "actual_prices = [p for p in prices if 1 < p < 3]\n",
    "actual_fruits = sorted(fruits, key=lambda name: name[-1])   # name[-1] is the last letter\n",
    "try:\n",
    "    actual_quantity = int(text)\n",
    "except ValueError:\n",
    "    actual_quantity = 0\n",
    "first, *actual_others = fruits\n",
    "\n",
    "### Your code starts here.\n",
    "predicted_prices = []\n",
    "predicted_fruits = []\n",
    "predicted_quantity = None\n",
    "predicted_others = []\n",
    "### Your code ends here.\n",
    "\n",
    "print(predicted_prices == actual_prices)\n",
    "print(predicted_fruits == actual_fruits)\n",
    "print(predicted_quantity == actual_quantity)\n",
    "print(predicted_others == actual_others)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c780723a",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "True"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "prices = [1.25, 0.5, 2.75, 3.1, 0.89]\n",
    "fruits = [\"apple\", \"banana\", \"mango\", \"kiwi\", \"fig\"]\n",
    "text = \"12a\"\n",
    "\n",
    "actual_prices = [p for p in prices if 1 < p < 3]\n",
    "actual_fruits = sorted(fruits, key=lambda name: name[-1])\n",
    "try:\n",
    "    actual_quantity = int(text)\n",
    "except ValueError:\n",
    "    actual_quantity = 0\n",
    "first, *actual_others = fruits\n",
    "\n",
    "predicted_prices = [1.25, 2.75]\n",
    "predicted_fruits = [\"banana\", \"apple\", \"fig\", \"kiwi\", \"mango\"]\n",
    "predicted_quantity = 0\n",
    "predicted_others = [\"banana\", \"mango\", \"kiwi\", \"fig\"]\n",
    "\n",
    "print(predicted_prices == actual_prices)\n",
    "print(predicted_fruits == actual_fruits)\n",
    "print(predicted_quantity == actual_quantity)\n",
    "print(predicted_others == actual_others)"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": ".venv (3.13.13)",
   "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
}
