{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "function-design-title",
   "metadata": {},
   "source": [
    "# Function Design\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9b6fb95",
   "metadata": {
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "# Find project root by looking for _config.yml\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "# Add project root to path\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "# Import shared teaching helpers and cell magics\n",
    "from shared import thinkpython, diagram, jupyturtle, structshape\n",
    "from shared.download import download\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "intro",
   "metadata": {},
   "source": [
    "Good functions are small, named clearly, documented when needed, and composed with other functions. This section focuses on scope, composition, docstrings, and basic lambda expressions.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a037c3fe",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aee17814-92f9-4744-8c8d-dd738767a67b",
   "metadata": {},
   "source": [
    "## Scope\n",
    "\n",
    "```{index} scope, local variable\n",
    "```\n",
    "\n",
    "Variables created inside functions are **local** to that function:\n",
    "\n",
    "```python\n",
    "def my_function():\n",
    "    local_var = 10  # Only exists inside the function\n",
    "    print(local_var)\n",
    "\n",
    "my_function()     # Prints: 10\n",
    "# print(local_var)  # Error: local_var doesn't exist here\n",
    "```\n",
    "\n",
    "Variables outside functions are **global**:\n",
    "\n",
    "```python\n",
    "global_var = 100  # Accessible everywhere\n",
    "\n",
    "def show_global():\n",
    "    print(global_var)  # Can read global variable\n",
    "\n",
    "show_global()  # Prints: 100\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9923f7df-8dcd-4a44-a6fb-dd70b36259bb",
   "metadata": {},
   "source": [
    "### Local vs. Global Scope\n",
    "\n",
    "When you create a variable (parameters or variables) inside a function, it is **local**, which means it exists only inside the function. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-9923f7df-8dcd-4a44-a",
   "metadata": {},
   "source": [
    "```{index} local scope, global scope, global keyword\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "117b3e61",
   "metadata": {},
   "source": [
    "A variable defined inside a function is by default local. Namely, it can not be accessed from outside of the function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c397c812-43db-4bb6-b695-797c75159329",
   "metadata": {},
   "outputs": [],
   "source": [
    "def greet():\n",
    "    message = \"Hello\"\n",
    "    print(message)\n",
    "\n",
    "greet()\n",
    "\n",
    "### try-except block to catch errors ==> next chapter\n",
    "try:\n",
    "    print(message)   ### cannot do this because message is local\n",
    "except NameError as error:\n",
    "    print(type(error).__name__)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "472ca529",
   "metadata": {},
   "source": [
    "So is a parameter defined in a function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "289dbdd5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "some message: Hello, World!\n",
      "NameError\n"
     ]
    }
   ],
   "source": [
    "def greet(message):\n",
    "    print(\"some message:\")  ### para not used in this function\n",
    "\n",
    "greet(\"Hello, World!\")\n",
    "\n",
    "### try-except block to catch errors ==> next chapter\n",
    "try:\n",
    "    print(message)   ### para message is local\n",
    "except NameError as error:\n",
    "    print(type(error).__name__)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77881fec",
   "metadata": {},
   "source": [
    "Now, let's look at the use of the `global` keyword. You will see that you can make a variable inside a function accessible from outside of the function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "977798e0-3256-44f9-a903-08bd7ef1c8a8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello\n",
      "Hello\n"
     ]
    }
   ],
   "source": [
    "def greet():\n",
    "    global message        ### global var: must declare first\n",
    "    message = \"Hello\"\n",
    "    print(message)\n",
    "\n",
    "greet()\n",
    "\n",
    "print(message)   ### can do! \"message\" variable is now global in the function definition.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b97534fe-43bb-41e1-80ab-c80fd15ba083",
   "metadata": {},
   "source": [
    "## Function Composition\n",
    "\n",
    "Function composition is the process of using the output of one function as the input to another. This can involve built-in functions, user-defined functions, or both."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-b97534fe-43bb-41e1-8",
   "metadata": {},
   "source": [
    "```{index} function composition\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1ce5984",
   "metadata": {},
   "source": [
    "Built-in functions can call other functions internally. For example, `sorted()` may call a function you pass with `key=`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6103f63d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Alexandra', 'Bob', 'Chen']\n",
      "['Bob', 'Chen', 'Alexandra']\n"
     ]
    }
   ],
   "source": [
    "names = [\"Bob\", \"Alexandra\", \"Chen\"]\n",
    "\n",
    "print(sorted(names))            ### default sort is alphabetical\n",
    "print(sorted(names, key=len))   ### sort by length of name; len is a function"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c593f3e4",
   "metadata": {},
   "source": [
    "For custom functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "7a2932f9-a9a2-4733-a480-934fbab6f54e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "36\n"
     ]
    }
   ],
   "source": [
    "def double(x):\n",
    "    return x * 2        ### x doubled\n",
    "\n",
    "def square(x):\n",
    "    return x ** 2       ### x squared\n",
    "\n",
    "result = square(double(3))      ### double(3) returns 6, then square(6) returns 36\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ex7-q-59a52e59",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Function Composition\n",
    "### Write three functions:\n",
    "### - calculate_area(length, width): returns the area\n",
    "### - format_result(value): returns 'Area is X square units'\n",
    "### Then write report_rectangle() that uses both to calculate and format.\n",
    "### Your code starts here:\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code stops here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ex7-a-4daaf03f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Area is 15 square units\n",
      "Area is 20 square units\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def calculate_area(length, width):\n",
    "    return length * width\n",
    "\n",
    "def format_result(value):\n",
    "    return f'Area is {value} square units'\n",
    "\n",
    "### Function composition: one function calls another\n",
    "def report_rectangle(length, width):\n",
    "    area = calculate_area(length, width)\n",
    "    return format_result(area)\n",
    "\n",
    "### Test\n",
    "print(report_rectangle(5, 3))\n",
    "print(report_rectangle(10, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fd25d1d",
   "metadata": {},
   "source": [
    "## Pure Functions and Side Effects\n",
    "\n",
    "A pure function is one that:\n",
    "\n",
    "- Given the same input, always returns the same output — no dependence on external state, randomness, or time.\n",
    "- Has no side effects: it doesn't modify anything outside itself (no mutating global variables, no writing to files, no printing, no changing arguments in place).\n",
    "\n",
    "A **pure function** computes a return value from its arguments without changing outside state. A **side effect** changes something outside the returned value: printing, mutating a list, editing a file, or changing a global variable.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-5fd25d1d",
   "metadata": {},
   "source": [
    "```{index} pure function, side effect\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f810b33c",
   "metadata": {},
   "source": [
    "Common ways functions become impure: \n",
    "- Mutating a mutable argument (like appending to a list passed in)\n",
    "- Reading or writing global variables\n",
    "- I/O: printing, reading files, network calls, database queries\n",
    "- Using random, datetime.now(), or other non-deterministic sources"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99f82e0d",
   "metadata": {},
   "source": [
    "Pure functions matter because:\n",
    "- Predictable/testable — no hidden state to set up or mock\n",
    "- Composable — safe to combine, reorder (where math allows), or memoize\n",
    "- Parallelizable — no shared mutable state means no race conditions\n",
    "- Easier to reason about — you can understand a pure function just by reading its body and signature\n",
    "\n",
    "Some Python tools assume purity:\n",
    "- `map()`, `filter()`, `functools.reduce()` work best with pure functions\n",
    "- `functools.lru_cache` (memoization) only makes sense if the function is pure — caching an impure function's results can produce wrong answers\n",
    "- Libraries like `dataclasses(frozen=True)` help enforce immutability, which supports writing pure functions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "147d6099",
   "metadata": {},
   "source": [
    "Pure functions are easier to test because the same inputs always produce the same outputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "dfca5e91",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "93\n",
      "93\n"
     ]
    }
   ],
   "source": [
    "def add_bonus(score, bonus):\n",
    "    return score + bonus\n",
    "\n",
    "print(add_bonus(88, 5))\n",
    "print(add_bonus(88, 5))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26e4a7b5",
   "metadata": {},
   "source": [
    "The next function has a side effect because it mutates the list passed to it. Sometimes mutation is useful, but it should be deliberate and visible from the function name or documentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50106510",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[85, 90, 95]\n"
     ]
    }
   ],
   "source": [
    "def add_bonus_in_place(scores, bonus):\n",
    "    for i in range(len(scores)):\n",
    "        scores[i] += bonus          ### assignment operator modifies the list in place\n",
    "\n",
    "quiz_scores = [80, 85, 90]          ### the outside var list is modified in place\n",
    "add_bonus_in_place(quiz_scores, 5)\n",
    "print(quiz_scores)\n",
    "\n",
    "### object changed"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99d864dd",
   "metadata": {},
   "source": [
    "The function below is impure because it depnds on external state and mutate input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "90a3a3f2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "total = 0\n",
    "\n",
    "def add_to_total(x):\n",
    "    global total\n",
    "    total += x\n",
    "    return total\n",
    "\n",
    "add_to_total(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "3d731726",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add_to_total(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "afbac196",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "15"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add_to_total(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64dbcbfc",
   "metadata": {},
   "source": [
    "As you see, `global` variables can have side effects: the function's result depends not only on `x`, but also on the value left behind by previous calls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "664b8b63",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Make the Function Pure\n",
    "# Rewrite add_bonus_in_place as a pure function named add_bonus_to_scores.\n",
    "# It should return a new list and leave the original scores unchanged.\n",
    "scores = [80, 85, 90]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "42b3693e",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "[80, 85, 90]\n",
      "[85, 90, 95]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def add_bonus_to_scores(scores, bonus):\n",
    "    updated = []\n",
    "    for score in scores:\n",
    "        updated.append(score + bonus)\n",
    "    return updated\n",
    "\n",
    "scores = [80, 85, 90]\n",
    "updated = add_bonus_to_scores(scores, 5)\n",
    "print(scores)\n",
    "print(updated)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f9c1720",
   "metadata": {},
   "source": [
    "## \"One Function, One Job\"\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-6f9c1720",
   "metadata": {},
   "source": [
    "```{index} single-purpose function, function design\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0fb589ce",
   "metadata": {},
   "source": [
    "Observe the functions below. You have to trace the flow to understand it. It seems trivial, but for good reasons."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "1f892402",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Row, row, row your boat\n",
      "Row, row, row your boat\n"
     ]
    }
   ],
   "source": [
    "def repeat(text):\n",
    "    print(text)\n",
    "    print(text)\n",
    "\n",
    "def first_two_lines(line):\n",
    "    repeat(line)\n",
    "\n",
    "def print_verse(line):\n",
    "    first_two_lines(line)\n",
    "\n",
    "# Example usage:\n",
    "print_verse(\"Row, row, row your boat\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bee21ecd",
   "metadata": {},
   "source": [
    "When you run `print_verse`, it calls `first_two_lines`, which calls `repeat`, which calls `print`. That's a lot of functions. Of course, we could have done the same thing with fewer functions, but the point of this example is to show how functions can work together.\n",
    "\n",
    "A good function usually does one job at one level of detail. If a function validates data, computes a result, formats output, and prints a message, it is harder to test and harder to reuse. Split the work into small functions and compose them. This is often summarized as often summarized as \"**one function, one job.**\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5cf01bac",
   "metadata": {},
   "source": [
    "For example, you could design a function that does several things:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "004ee472",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Order total: $50.00\n",
      "Error: invalid input\n"
     ]
    }
   ],
   "source": [
    "def process_order(price, quantity):\n",
    "    if price < 0 or quantity < 0:\n",
    "        print(\"Error: invalid input\")\n",
    "        return                          ### like break statement, but exit the \"function\" early\n",
    "    total = price * quantity\n",
    "    if total > 100:\n",
    "        total *= 0.9  # apply discount\n",
    "    formatted = f\"${total:.2f}\"\n",
    "    print(f\"Order total: {formatted}\")\n",
    "    \n",
    "process_order(10, 5)    # valid input\n",
    "process_order(-5, 10)   # invalid input"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e37354d2",
   "metadata": {},
   "source": [
    "Or, we can split it into small, single-purpose functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f4ac92fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Order total: $450.00\n",
      "Error: invalid input\n"
     ]
    }
   ],
   "source": [
    "def is_valid_order(price, quantity):\n",
    "    return price >= 0 and quantity >= 0\n",
    "\n",
    "def compute_total(price, quantity):\n",
    "    total = price * quantity\n",
    "    if total > 100:\n",
    "        total *= 0.9\n",
    "    return total\n",
    "\n",
    "def format_currency(amount):\n",
    "    return f\"${amount:.2f}\"\n",
    "\n",
    "def process_order(price, quantity):\n",
    "    if not is_valid_order(price, quantity):\n",
    "        print(\"Error: invalid input\")\n",
    "        return\n",
    "    total = compute_total(price, quantity)\n",
    "    print(f\"Order total: {format_currency(total)}\")\n",
    "    \n",
    "process_order(100, 5)    # valid input\n",
    "process_order(-5, 10)   # invalid input"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c7b5f0b",
   "metadata": {},
   "source": [
    "Why the second version is better?\n",
    "\n",
    "- `is_valid_order` and `compute_total` are pure functions (same input ==> same output, no side effects). They can be tested directly without capturing printed output.\n",
    "- `format_currency` is reusable anywhere else in the program that needs to display money.\n",
    "- `process_order` becomes a thin orchestrator. It reads almost like a sentence describing the steps, and it's the only function that touches I/O (`print`)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1b62364",
   "metadata": {},
   "source": [
    "Another example of on-single-purpose function that mashes things (averaging, grading, formatting, and printing) all into one function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "d9e3764f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Maya: 91.3 (A)\n"
     ]
    }
   ],
   "source": [
    "def summarize_student(name, scores):\n",
    "    total = 0\n",
    "    for s in scores:\n",
    "        total += s\n",
    "    average = total / len(scores)\n",
    "\n",
    "    if average >= 90:\n",
    "        grade = \"A\"\n",
    "    elif average >= 80:\n",
    "        grade = \"B\"\n",
    "    elif average >= 70:\n",
    "        grade = \"C\"\n",
    "    else:\n",
    "        grade = \"Needs review\"\n",
    "\n",
    "    print(f\"{name}: {average:.1f} ({grade})\")\n",
    "\n",
    "summarize_student(\"Maya\", [92, 87, 95])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec832e09",
   "metadata": {},
   "source": [
    "Why this is not a good function design:\n",
    "\n",
    "- It computes, decides, formats, and prints all in one place, so you can't test the average or the grading logic independently — you'd have to capture **stdout** just to check if 92, 87, 95 averages correctly.\n",
    "- It also **returns nothing** (`None`), so the caller has no way to reuse the summary string elsewhere (e.g., writing it to a file, building a report, or displaying it in a different format) — printing is baked in rather than left to the caller.\n",
    "- The averaging logic and grading logic can't be reused for other purposes (e.g., grading a whole class, or computing an average without a grade attached)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df264537",
   "metadata": {},
   "source": [
    "In comparison, the design below is easier to change. If the grading rule changes, edit `letter_grade`. If the average calculation changes, edit `mean`. The caller can keep using `summarize_student`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "20d2730b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Maya: 91.3 (A)\n"
     ]
    }
   ],
   "source": [
    "def mean(values):\n",
    "    return sum(values) / len(values)\n",
    "\n",
    "def letter_grade(score):\n",
    "    if score >= 90:\n",
    "        return \"A\"\n",
    "    if score >= 80:\n",
    "        return \"B\"\n",
    "    if score >= 70:\n",
    "        return \"C\"\n",
    "    return \"Needs review\"\n",
    "\n",
    "def summarize_student(name, scores):\n",
    "    average = mean(scores)\n",
    "    grade = letter_grade(average)\n",
    "    return f\"{name}: {average:.1f} ({grade})\"\n",
    "\n",
    "print(summarize_student(\"Maya\", [92, 87, 95]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "1527c7d6",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Compose Small Functions\n",
    "# Write three functions:\n",
    "# 1. celsius_to_fahrenheit(c)\n",
    "# 2. is_hot(f), which returns True when f is at least 85\n",
    "# 3. weather_label(c), which returns \"hot\" or \"not hot\" for a Celsius temperature\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "af3a31b0",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hot\n",
      "not hot\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def celsius_to_fahrenheit(c):\n",
    "    return c * 9 / 5 + 32\n",
    "\n",
    "def is_hot(f):\n",
    "    return f >= 85\n",
    "\n",
    "def weather_label(c):\n",
    "    f = celsius_to_fahrenheit(c)\n",
    "    if is_hot(f):\n",
    "        return \"hot\"\n",
    "    return \"not hot\"\n",
    "\n",
    "print(weather_label(30))\n",
    "print(weather_label(20))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "105e0774-6927-4c40-866d-58264f19f216",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Docstrings\n",
    "\n",
    "**Docstrings** (**documentation** strings) are used to document **functions**/methods, _classes_, and _modules_. They use _triple quotes_ and should be the first statement after defining a function or class. \n",
    "\n",
    "Always document your functions with docstrings:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-105e0774-6927-4c40-8",
   "metadata": {},
   "source": [
    "```{index} docstring\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "95498a60",
   "metadata": {},
   "outputs": [],
   "source": [
    "### Function with docstring\n",
    "def greet(name):\n",
    "    \"\"\"\n",
    "    This function does xxx and yyy.         ### 1. what this function is about\n",
    "    \n",
    "    Args:                                   ### 2. input parameters\n",
    "        name: The person's name (string)    \n",
    "    \n",
    "    Returns:                                ### 3. what the function returns\n",
    "        A greeting message (string)\n",
    "    \"\"\"\n",
    "    return f\"Hello, {name}!\"\n",
    "\n",
    "message = greet(\"Homer\")       ### call the function"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5dbe1c8-83ec-4ef7-bb72-f936e4806a93",
   "metadata": {},
   "source": [
    "As an example:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f1bb7d6-611f-4af5-979d-9f91fb0e2bea",
   "metadata": {},
   "source": [
    "```python\n",
    "def calculate_bmi(weight, height):\n",
    "    \"\"\"\n",
    "    Calculate Body Mass Index (BMI).\n",
    "    \n",
    "    Args:\n",
    "        weight: Weight in kilograms (float)\n",
    "        height: Height in meters (float)\n",
    "    \n",
    "    Returns:\n",
    "        BMI value (float)\n",
    "    \n",
    "    Example:\n",
    "        >>> calculate_bmi(70, 1.75)\n",
    "        22.86\n",
    "    \"\"\"\n",
    "    return weight / (height ** 2)\n",
    "```\n",
    "\n",
    "Good docstrings include:\n",
    "1. What the function does\n",
    "2. Parameters and their types\n",
    "3. What the function returns\n",
    "4. Usage examples (optional)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4bef9858-6692-4dc9-b2bf-534c14390028",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Testing calculate_discount:\n",
      "  $100 with 20% off = $80.0\n",
      "\n",
      "Testing is_valid_email:\n",
      "  'user@example.com' is valid: True\n",
      "  'invalid-email' is valid: False\n",
      "\n",
      "Testing celsius_to_fahrenheit:\n",
      "  0°C = 32.0°F\n",
      "  100°C = 212.0°F\n",
      "  37°C = 98.6°F\n"
     ]
    }
   ],
   "source": [
    "### Practical functions with docstrings\n",
    "\n",
    "def calculate_discount(price, discount_percent):\n",
    "    \"\"\"\n",
    "    Calculate the final price after applying a discount.\n",
    "    \n",
    "    Args:\n",
    "        price: Original price (float or int)\n",
    "        discount_percent: Discount percentage (0-100)\n",
    "    \n",
    "    Returns:\n",
    "        Final price after discount (float)\n",
    "    \"\"\"\n",
    "    discount_amount = price * (discount_percent / 100)\n",
    "    final_price = price - discount_amount\n",
    "    return final_price\n",
    "\n",
    "def is_valid_email(email):\n",
    "    \"\"\"\n",
    "    Check if email has basic valid format.\n",
    "    \n",
    "    Args:\n",
    "        email: Email address to validate (str)\n",
    "    \n",
    "    Returns:\n",
    "        True if email contains @ and ., False otherwise\n",
    "    \"\"\"\n",
    "    return '@' in email and '.' in email\n",
    "\n",
    "def celsius_to_fahrenheit(celsius):\n",
    "    \"\"\"\n",
    "    Convert Celsius to Fahrenheit.\n",
    "    \n",
    "    Args:\n",
    "        celsius: Temperature in Celsius\n",
    "    \n",
    "    Returns:\n",
    "        Temperature in Fahrenheit\n",
    "    \"\"\"\n",
    "    return (celsius * 9/5) + 32\n",
    "\n",
    "### Test the functions\n",
    "print(\"Testing calculate_discount:\")\n",
    "original = 100\n",
    "discount = 20\n",
    "final = calculate_discount(original, discount)\n",
    "print(f\"  ${original} with {discount}% off = ${final}\")\n",
    "\n",
    "print(\"\\nTesting is_valid_email:\")\n",
    "print(f\"  'user@example.com' is valid: {is_valid_email('user@example.com')}\")\n",
    "print(f\"  'invalid-email' is valid: {is_valid_email('invalid-email')}\")\n",
    "\n",
    "print(\"\\nTesting celsius_to_fahrenheit:\")\n",
    "print(f\"  0°C = {celsius_to_fahrenheit(0)}°F\")\n",
    "print(f\"  100°C = {celsius_to_fahrenheit(100)}°F\")\n",
    "print(f\"  37°C = {celsius_to_fahrenheit(37):.1f}°F\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "ex8-q-8a5c47d0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Writing Good Docstrings\n",
    "### Write a function called validate_password() that:\n",
    "### - Takes a password string as a parameter\n",
    "### - Checks if it's at least 8 characters long\n",
    "### - Returns True if valid, False otherwise\n",
    "### Include a comprehensive docstring with description, Args, and Returns sections.\n",
    "\n",
    "### Your code starts here:\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "ex8-a-e14ff35b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def validate_password(password):\n",
    "    \"\"\"\n",
    "    Validate if a password meets minimum length requirements.\n",
    "    \n",
    "    Args:\n",
    "        password (str): The password to validate\n",
    "    \n",
    "    Returns:\n",
    "        bool: True if password is at least 8 characters, False otherwise\n",
    "    \"\"\"\n",
    "    return len(password) >= 8\n",
    "\n",
    "### Test the function\n",
    "print(validate_password(\"short\"))        ### False\n",
    "print(validate_password(\"verylongpassword\"))  ### True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3a3123a",
   "metadata": {},
   "source": [
    "### Docstrings as Contracts\n",
    "\n",
    "A docstring should tell a reader what the function expects and what it returns. For student code, a short docstring is enough when it states the purpose, important assumptions, and return value."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-c3a3123a",
   "metadata": {},
   "source": [
    "```{index} function contract\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "bb6b6877",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "84.0\n"
     ]
    }
   ],
   "source": [
    "def normalized_score(points, total):\n",
    "    \"\"\"Return points as a percentage of total.\n",
    "\n",
    "    Args:\n",
    "        points: Earned points.\n",
    "        total: Possible points. Must be greater than zero.\n",
    "\n",
    "    Returns:\n",
    "        Percentage score as a float.\n",
    "    \"\"\"\n",
    "    return points / total * 100\n",
    "\n",
    "print(normalized_score(42, 50))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "4fcd1d01",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "0.75\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Write a Contract Docstring\n",
    "# Add a docstring to passing_rate. The docstring should state what scores means,\n",
    "# what cutoff means, and what the function returns.\n",
    "def passing_rate(scores, cutoff=70):\n",
    "    passed = []\n",
    "    for score in scores:\n",
    "        if score >= cutoff:\n",
    "            passed.append(score)\n",
    "    return len(passed) / len(scores)\n",
    "\n",
    "print(passing_rate([80, 64, 90, 72]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "1608aa9f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "0.75\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def passing_rate(scores, cutoff=70):\n",
    "    \"\"\"Return the proportion of scores greater than or equal to cutoff.\n",
    "\n",
    "    Args:\n",
    "        scores: A non-empty list of numeric scores.\n",
    "        cutoff: Minimum score counted as passing.\n",
    "\n",
    "    Returns:\n",
    "        A float between 0 and 1.\n",
    "    \"\"\"\n",
    "    passed = []\n",
    "    for score in scores:\n",
    "        if score >= cutoff:\n",
    "            passed.append(score)\n",
    "    return len(passed) / len(scores)\n",
    "\n",
    "print(passing_rate([80, 64, 90, 72]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c46d682b",
   "metadata": {},
   "source": [
    "## Lambda Functions\n",
    "\n",
    "**Syntax:** \n",
    "\n",
    "`lambda arguments: expression`\n",
    "\n",
    "Lambda functions are small, **anonymous** functions that can have any number of arguments but can only have one expression. They are useful for short, simple functions that you don't want to define formally.\n",
    "\n",
    "Rule of thumb: lambdas are best for short, throwaway functions passed inline to something like sorted, map, or filter — not for anything that needs a docstring, multiple lines, or a name people will call more than once."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-c46d682b",
   "metadata": {},
   "source": [
    "```{index} lambda function, anonymous function\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ef797aa",
   "metadata": {},
   "source": [
    "### Lambda Limitations\n",
    "\n",
    "- Can only contain expressions, not statements\n",
    "- Cannot contain assignments, print statements, or other statements\n",
    "- Best for simple, one-line functions\n",
    "- For complex logic, use regular functions (`def`)\n",
    "\n",
    "If you find yourself writing a multi-line `lambda`, switch to a normal `def` function instead."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-9ef797aa",
   "metadata": {},
   "source": [
    "```{index} key function, sorted()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31ac93fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "25\n",
      "7\n"
     ]
    }
   ],
   "source": [
    "### Basic lambda function\n",
    "square = lambda x: x ** 2\n",
    "print(square(5))  # Output: 25"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "babb0938",
   "metadata": {},
   "source": [
    "This lambda function is equivalent to:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "3f83f23c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def square(x):\n",
    "    return x ** 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64f133f9",
   "metadata": {},
   "source": [
    "More examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0491865a",
   "metadata": {},
   "outputs": [],
   "source": [
    "### Lambda with multiple arguments\n",
    "add = lambda x, y: x + y\n",
    "print(add(3, 4))  # Output: 7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "911632c8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "is_even = lambda n: n % 2 == 0\n",
    "is_even(6)  # True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e31e62d",
   "metadata": {},
   "source": [
    "Lambda functions are actually useful when serving as arguments to other functions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "09af163d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('Maya', 92), ('Lee', 85), ('Sam', 78)]"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "students = [(\"Maya\", 92), (\"Sam\", 78), (\"Lee\", 85)]\n",
    "\n",
    "# Sort by score instead of name\n",
    "sorted(students, key=lambda s: s[1])\n",
    "# [('Sam', 78), ('Lee', 85), ('Maya', 92)]\n",
    "\n",
    "# Sort by score, descending\n",
    "sorted(students, key=lambda s: s[1], reverse=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2cc7c0d",
   "metadata": {},
   "source": [
    "Or serving as a `dict` value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "4e33af44",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "operations = {\n",
    "    \"add\": lambda a, b: a + b,\n",
    "    \"sub\": lambda a, b: a - b,\n",
    "    \"mul\": lambda a, b: a * b,\n",
    "}\n",
    "operations[\"mul\"](3, 4)  # 12"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9b2396d",
   "metadata": {},
   "source": [
    "If the logic needs a name for clarity, more than one line, or will be reused, use a regular def instead. This connects back to the single-purpose principle."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-closures",
   "metadata": {},
   "source": [
    "## Closures\n",
    "\n",
    "In the Scope section, you saw two places a name can live: inside a function (local) and at the top level of the program (global). A function can also be defined *inside* another function. This **nested function** can read the outer function's variables, which live in the **enclosing scope**. When Python looks up a name, it searches the scopes in this order: local, enclosing, global, then built-in."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-closures-index",
   "metadata": {},
   "source": [
    "```{index} closure, nested function, enclosing scope\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch04-nested-function",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Alice!\n",
      "Hello, Bob!\n"
     ]
    }
   ],
   "source": [
    "def greet_all(names):\n",
    "    greeting = \"Hello\"                  ### local to greet_all; enclosing scope for greet\n",
    "\n",
    "    def greet(name):                    ### nested function\n",
    "        print(f\"{greeting}, {name}!\")   ### reads greeting from the enclosing scope\n",
    "\n",
    "    for name in names:\n",
    "        greet(name)\n",
    "\n",
    "greet_all([\"Alice\", \"Bob\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-function-factory",
   "metadata": {},
   "source": [
    "### Functions That Return Functions\n",
    "\n",
    "An outer function can also *return* its inner function. The returned function still remembers the enclosing variables after the outer function has finished. A function that remembers values from the scope where it was created is called a **closure**. An outer function that builds and returns configured closures is called a **function factory**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-function-factory-index",
   "metadata": {},
   "source": [
    "```{index} function factory\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch04-make-multiplier",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "30\n"
     ]
    }
   ],
   "source": [
    "def make_multiplier(factor):\n",
    "    def multiply(x):\n",
    "        return x * factor          ### factor comes from the enclosing call\n",
    "    return multiply                ### return the function itself, not multiply(...)\n",
    "\n",
    "double = make_multiplier(2)\n",
    "triple = make_multiplier(3)\n",
    "\n",
    "print(double(10))    # 20\n",
    "print(triple(10))    # 30"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-closure-lambda-text",
   "metadata": {},
   "source": [
    "Each call to `make_multiplier()` creates a new `multiply` function with its own remembered `factor`: `double` remembers `2`, and `triple` remembers `3`. Notice that `make_multiplier` returns `multiply` without parentheses, so it returns the function object rather than the result of calling it.\n",
    "\n",
    "When the returned function only computes one expression, a lambda works too:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch04-closure-lambda",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "36.0\n",
      "30.0\n"
     ]
    }
   ],
   "source": [
    "def make_discount(rate):\n",
    "    return lambda price: round(price * (1 - rate), 2)   ### closure over rate\n",
    "\n",
    "student_price = make_discount(0.10)\n",
    "member_price = make_discount(0.25)\n",
    "\n",
    "print(student_price(40))    # 36.0\n",
    "print(member_price(40))     # 30.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-nonlocal",
   "metadata": {},
   "source": [
    "### Changing an Enclosing Variable with `nonlocal`\n",
    "\n",
    "A closure can *read* an enclosing variable freely, but assigning to that name inside the inner function creates a new local variable instead. To update the enclosing variable, declare it **`nonlocal`**, much as `global` declares a global variable. This lets a closure keep private state between calls, such as a counter:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-nonlocal-index",
   "metadata": {},
   "source": [
    "```{index} nonlocal\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch04-make-counter",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "def make_counter():\n",
    "    count = 0\n",
    "    def increment():\n",
    "        nonlocal count          ### update count in the enclosing scope\n",
    "        count += 1\n",
    "        return count\n",
    "    return increment\n",
    "\n",
    "click = make_counter()\n",
    "print(click())    # 1\n",
    "print(click())    # 2\n",
    "print(click())    # 3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch04-closure-wrapup",
   "metadata": {},
   "source": [
    "Unlike the `global total` example in the Pure Functions section, the counter's state is private: no other code can change `count` except by calling `click()`. Closures are also the foundation of **decorators**, which you will meet in Chapter 10."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch04-closure-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Function Factory\n",
    "# Write make_greeting(greeting), which returns a function that takes a name\n",
    "# and returns the string \"<greeting>, <name>!\".\n",
    "# Test:\n",
    "#   hello = make_greeting(\"Hello\")\n",
    "#   hi = make_greeting(\"Hi\")\n",
    "#   print(hello(\"Alice\"))   # Hello, Alice!\n",
    "#   print(hi(\"Bob\"))        # Hi, Bob!\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch04-closure-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Alice!\n",
      "Hi, Bob!\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def make_greeting(greeting):\n",
    "    def greet(name):\n",
    "        return f\"{greeting}, {name}!\"\n",
    "    return greet\n",
    "\n",
    "hello = make_greeting(\"Hello\")\n",
    "hi = make_greeting(\"Hi\")\n",
    "print(hello(\"Alice\"))\n",
    "print(hi(\"Bob\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e237f449",
   "metadata": {},
   "source": []
  }
 ],
 "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
}
