{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a14edb7e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "# Python Basic Syntax"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cbefe58a-9ea2-44f3-8987-5d095422f9a0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "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  # ← Add project root, not chapters\n",
    "        break\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "from shared import thinkpython, diagram, jupyturtle, download\n",
    "\n",
    "# # Register as top-level modules so direct imports work in subsequent cells\n",
    "sys.modules['thinkpython'] = thinkpython\n",
    "sys.modules['diagram'] = diagram\n",
    "sys.modules['jupyturtle'] = jupyturtle\n",
    "sys.modules['download'] = download"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "622e407b",
   "metadata": {},
   "source": [
    "Python's syntax is small, but it is strict about layout. This section covers how indentation defines blocks, how statements are formatted, how to display output and read input, how to write comments, and how to use built-in functions, objects, modules, keywords, and error messages."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "633d687b-d447-4305-b6d3-01de9cd7e71d",
   "metadata": {},
   "source": [
    "```{figure} ../../figures/python-syntax-overview.svg\n",
    "---\n",
    "name: python-syntax-overview\n",
    "width: 80%\n",
    "---\n",
    "The Python syntax topics in this section\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2981b69c",
   "metadata": {},
   "source": [
    "## Indentation and Block Structure"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5edacc6",
   "metadata": {},
   "source": [
    "```{index} indentation, block structure\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb4a048d",
   "metadata": {},
   "source": [
    "In Python, **indentation** defines **code blocks** instead of braces (`{}`), which many other languages use. Any line ending with a colon (`:`), such as `if`, `for`, `while`, `def`, or `class`, starts a new block, and the indented lines that follow belong to that block. Python expects consistent indentation (commonly `4` spaces per level), and mixing tabs and spaces or misaligning lines can raise `IndentationError`. When indentation changes, Python treats that as entering or leaving a block, so correct spacing controls program structure and execution flow."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13fa1498",
   "metadata": {},
   "source": [
    "```text\n",
    "for i in range(5):\n",
    "print(i)                ### This line is not indented, so it will cause an error\n",
    "```\n",
    "\n",
    "Output    \n",
    "```text\n",
    "Cell In[2], line 2\n",
    "    print(i)                ### This line is not indented, so it will cause an error\n",
    "    ^\n",
    "IndentationError: expected an indented block after 'for' statement on line 1\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a7b0a4c8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    print(i)            ### This line is indented, so it will work correctly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d5cd364c",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Fix indentation\n",
    "# The code below should print three lines: 0, 1, and 2.\n",
    "# Replace the pass statement with print(i), keeping it indented inside the loop.\n",
    "for i in range(3):\n",
    "    ### Your code starts here.\n",
    "    pass\n",
    "    ### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "97fde22f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "for i in range(3):\n",
    "    print(i)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9c50c2c",
   "metadata": {},
   "source": [
    "## Statement Formatting"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3afbf059",
   "metadata": {},
   "source": [
    "```{index} statement; formatting, line continuation\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e4c35cf",
   "metadata": {},
   "source": [
    "In Python, a statement usually ends at a newline, so each line is typically one statement. You can place multiple simple statements on one line using semicolons (`;`), but this is generally **discouraged** because it reduces readability. For long statements, Python allows implicit line continuation inside parentheses `()`, brackets `[]`, or braces `{}`, which is the preferred way to split expressions across lines. Explicit continuation with a backslash (`\\`) also works, but it is fragile because a trailing space after the backslash will cause an error. In practice, write one statement per line and use **parentheses** for **multi-line expressions**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "22994888",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30\n"
     ]
    }
   ],
   "source": [
    "### 1) Newlines: one statement per line (preferred)\n",
    "x = 10\n",
    "y = 20\n",
    "total = x + y\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "e91c2739",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30\n"
     ]
    }
   ],
   "source": [
    "### 2) Semicolons: multiple statements on one line (valid, but less readable)\n",
    "x = 10; y = 20; print(x + y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "f1617a2c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "600\n"
     ]
    }
   ],
   "source": [
    "### 3) Multi-line with parentheses (preferred)\n",
    "total = (\n",
    "    100\n",
    "    + 200\n",
    "    + 300\n",
    ")\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2691c294",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "600\n"
     ]
    }
   ],
   "source": [
    "### 4) Multi-line with backslash (works, but less preferred)\n",
    "total = 100 + 200 + \\\n",
    "        300\n",
    "print(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3af84925",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name: Alice Age: 25\n"
     ]
    }
   ],
   "source": [
    "### 5) Multi-line function call with parentheses\n",
    "print(\n",
    "    \"Name:\", \"Alice\",\n",
    "    \"Age:\", 25\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "d252bc57",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Split a long expression\n",
    "# Rewrite the calculation of total inside parentheses across multiple lines.\n",
    "# The answer should still print 46.5.\n",
    "base_price = 32\n",
    "shipping = 7.5\n",
    "tax = 7\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "1d00afdf",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "46.5\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "base_price = 32\n",
    "shipping = 7.5\n",
    "tax = 7\n",
    "\n",
    "total = (\n",
    "    base_price\n",
    "    + shipping\n",
    "    + tax\n",
    ")\n",
    "\n",
    "print(total)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "143a1c10",
   "metadata": {},
   "source": [
    "## Input and Output\n",
    "\n",
    "Programs communicate through output and input. This section shows how `print()` displays values and how f-strings format them, then how `input()` reads text from the user and how to convert that text into numbers."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a427552a",
   "metadata": {
    "vscode": {
     "languageId": "markdown"
    }
   },
   "source": [
    "### `print()`\n",
    "\n",
    "In Python, the **`print()`** function displays output on the screen. It is one of the most commonly used functions for debugging, showing results, and interacting with users.\n",
    "\n",
    "The `print()` function displays values to the console/command line:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b58d15f",
   "metadata": {},
   "source": [
    "```{index} print()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "0944cf1c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello, world!\n"
     ]
    }
   ],
   "source": [
    "print(\"hello, world!\")           ### print a string"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5cf5eb65-c9a0-45be-a38f-49916fb24558",
   "metadata": {},
   "source": [
    "To print multiple values in one statement, you either **comma-separate** your values or **concatenate** the strings. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "26645ab0-7453-4c86-9bb5-d5799e6e3bb7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name: Alice Age: 25\n",
      "Name: Alice Age: 25\n"
     ]
    }
   ],
   "source": [
    "print(\"Name:\", \"Alice\", \"Age:\", 25)       ### commas-separated\n",
    "print(\"Name:\" + \" Alice\" + \" Age:\", 25)   ### + concatenated"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "d1aee52c",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "can only concatenate str (not \"int\") to str",
     "output_type": "error",
     "traceback": [
      "\u001b[31mTypeError\u001b[39m\u001b[31m:\u001b[39m can only concatenate str (not \"int\") to str\n"
     ]
    }
   ],
   "source": [
    "%%expect TypeError\n",
    "\n",
    "print(\"I am \" + 25 + \" years old\")      ### Error: can only concatenate str (not \"int\") to str"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2962a01c",
   "metadata": {},
   "source": [
    "#### Print Function Parameters\n",
    "\n",
    "The `print()` function has optional parameters: \n",
    "- `object(s)`: one or more values to print. All are converted to strings before printing.\n",
    "- `sep`: the string placed between objects; the default is a space.\n",
    "- `end`: the string added at the end of the output; the default is a newline (`\"\\n\"`).\n",
    "- `file`: the output destination; the default is `sys.stdout`.\n",
    "- `flush`: if `True`, forces immediate output; the default is `False`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6ddc5db8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A B C (separator is space by default)\n",
      "A-B-C\n",
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "0 1 2 3 4 "
     ]
    }
   ],
   "source": [
    "### sep\n",
    "print(\"A\", \"B\", \"C\", \"(separator is space by default)\")   ### Output: A B C (separator is space by default)\n",
    "print(\"A\", \"B\", \"C\", sep=\"-\")   ### Output: A-B-C (separator changed to '-')\n",
    "\n",
    "### end\n",
    "# list 1: print with different end characters\n",
    "for num in range(5):\n",
    "    print(num)                  ### Print numbers on separate lines\n",
    "# list 2: print with different end characters\n",
    "for num in range(5):\n",
    "    print(num, end=\" \")         ### Print numbers on the same line separated by space"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "12064b21",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Print \"hello, world\"\n",
    "### The output should look the same as the cell below\n",
    "### Your code begins here\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "75552105-2f26-4551-9616-cd03fc1646db",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello, world\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "print(\"hello, world\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ff6ed2f",
   "metadata": {},
   "source": [
    "### F-Strings \n",
    "\n",
    "**F-strings** (formatted string literals) are a readable and efficient way to format strings in Python (available since Python 3.6). An f-string is often preferred because it is concise and allows **expressions** inside `{}`, so you do not need to manually convert values to strings:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "2b91bc92",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "My name is Alice and I am 25 years old.\n",
      "The sum of 10 and 20 is 30\n"
     ]
    }
   ],
   "source": [
    "name = \"Alice\"\n",
    "age = 25\n",
    "print(f\"My name is {name} and I am {age} years old.\")   ### f-string with variables\n",
    "\n",
    "x = 10\n",
    "y = 20\n",
    "print(f\"The sum of {x} and {y} is {x + y}\")             ### f-string with expressions\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "530efb31-b92d-428a-ad00-ea30da0a4d60",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "f-string formatting: Score: 87/100 (87.0%)\n",
      "Score: 87/100 (87.0%)\n",
      "\n",
      "Alternative formatting:\n",
      "Score: 87/100 (87.0%)\n"
     ]
    }
   ],
   "source": [
    "score = 87\n",
    "possible = 100\n",
    "print(f\"f-string formatting: Score: {score}/{possible} ({score / possible:.1%})\")\n",
    "print(f\"Score: {score}/{possible} ({score / possible:.1%})\")\n",
    "\n",
    "print(f\"\\nAlternative formatting:\")\n",
    "print(\"Score: {}/{} ({}%)\".format(score, possible, score / possible * 100))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-fmtspec-md",
   "metadata": {},
   "source": [
    "### Format Specifications\n",
    "\n",
    "Inside the braces of an f-string, you can add a colon followed by a **format specification** that controls how the value is displayed. You already saw one above: `{score / possible:.1%}` shows a fraction as a percentage. The most common format specifications are:\n",
    "\n",
    "- `:.2f` shows a number with exactly 2 decimal places (fixed-point) and keeps trailing zeros.\n",
    "- `:,` inserts commas as thousands separators.\n",
    "- `:.1%` multiplies the value by 100 and shows it as a percentage with 1 decimal place.\n",
    "- `:>8` right-aligns the value in a field 8 characters wide (`<` aligns left and `^` centers).\n",
    "\n",
    "You can combine them, as in `:,.2f`, which adds thousands separators and shows 2 decimal places."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-fmtspec-idx",
   "metadata": {},
   "source": [
    "```{index} format specification, f-string\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-fmtspec-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Price: $4.50\n",
      "Revenue: 1,234,567.89\n",
      "Growth: 8.3%\n",
      "|   apple|apple   |\n"
     ]
    }
   ],
   "source": [
    "price = 4.5\n",
    "revenue = 1234567.891\n",
    "growth = 0.083\n",
    "item = \"apple\"\n",
    "\n",
    "print(f\"Price: ${price:.2f}\")        ### 2 decimal places\n",
    "print(f\"Revenue: {revenue:,.2f}\")    ### thousands separator and 2 decimal places\n",
    "print(f\"Growth: {growth:.1%}\")       ### percentage with 1 decimal place\n",
    "print(f\"|{item:>8}|{item:<8}|\")      ### right-aligned and left-aligned in 8 characters"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-fmtspec-round-md",
   "metadata": {},
   "source": [
    "A format specification is different from `round()`. The `round()` function returns a number, and Python displays numbers without trailing zeros, so `round(42.5, 2)` still shows `42.5`. A format specification produces text, so it shows exactly the number of decimal places you ask for. Use `round()` when you need a rounded value for further calculation, and use a format specification when you want to control how a value looks in output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-fmtspec-round-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "42.5\n",
      "42.50\n"
     ]
    }
   ],
   "source": [
    "print(round(42.5, 2))     ### 42.5: round() returns a number, so the trailing zero is dropped\n",
    "print(f\"{42.5:.2f}\")      ### 42.50: the format specification keeps 2 decimal places"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "220da0e9",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Format a dataset summary\n",
    "# Use the variables below.\n",
    "# Print exactly these two lines:\n",
    "# sales: 128 rows x 5 columns\n",
    "# sales|128|5\n",
    "# Use an f-string for the first line.\n",
    "# Use print() with sep=\"|\" for the second line.\n",
    "dataset_name = \"sales\"\n",
    "row_count = 128\n",
    "column_count = 5\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "40b5c1d9",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sales: 128 rows x 5 columns\n",
      "sales|128|5\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "dataset_name = \"sales\"\n",
    "row_count = 128\n",
    "column_count = 5\n",
    "\n",
    "print(f\"{dataset_name}: {row_count} rows x {column_count} columns\")\n",
    "print(dataset_name, row_count, column_count, sep=\"|\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-fmtspec-ex",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Format a price report\n",
    "# Use f-strings with format specifications.\n",
    "# Print exactly these three lines:\n",
    "# Unit price: $8.50\n",
    "# Total sales: 12,750.00\n",
    "# Discount: 15.0%\n",
    "unit_price = 8.5\n",
    "total_sales = 12750\n",
    "discount_rate = 0.15\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-fmtspec-sol",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Unit price: $8.50\n",
      "Total sales: 12,750.00\n",
      "Discount: 15.0%\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "unit_price = 8.5\n",
    "total_sales = 12750\n",
    "discount_rate = 0.15\n",
    "\n",
    "print(f\"Unit price: ${unit_price:.2f}\")\n",
    "print(f\"Total sales: {total_sales:,.2f}\")\n",
    "print(f\"Discount: {discount_rate:.1%}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0d49480-2e7f-4828-b277-78ad9a6353e5",
   "metadata": {},
   "source": [
    "```{index} input(), keyboard input\n",
    "```\n",
    "### Keyboard Input\n",
    "\n",
    "\n",
    "Python provides a built-in function called `input` that stops the program and waits for the user to type something. When the user presses *Return* or *Enter*, the program resumes, and `input` returns what the user typed as a **string**. Before getting user input, you might want to display a **prompt** that explains what to type. The `input` syntax is:\n",
    "```\n",
    "variable = input(\"Prompt message: \")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ba6c07a",
   "metadata": {},
   "source": [
    "Run the following examples. When a cell asks for input, type your answer in the box under the cell and press Enter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e42ddf9-f84f-429c-89f7-b6e09ee9b8e7",
   "metadata": {
    "tags": [
     "skip-execution"
    ]
   },
   "outputs": [],
   "source": [
    "name = input(\"Enter your name: \")\n",
    "print(\"Hello, \" + name + \"!\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f8c39e7-9898-4a0e-99aa-f04d063fd008",
   "metadata": {},
   "source": [
    "### Type Conversion\n",
    "\n",
    "The user input will be a string type, so if you expect the user to type an integer, you can use the `int` function to convert the return value to `int`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-0f8c39e7-9898-4a0e-9",
   "metadata": {},
   "source": [
    "```{index} type conversion, int(), input()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "968bee9e-5fbf-43a9-acc6-03af0dfbbd4f",
   "metadata": {
    "tags": [
     "skip-execution"
    ]
   },
   "outputs": [],
   "source": [
    "age = input(\"Enter your age: \")\n",
    "\n",
    "print(type(age))                      ### age is of string type\n",
    "age = int(age)                        ### convert input string to integer\n",
    "\n",
    "print(type(age))\n",
    "print(f\"You are {age} years old.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a63aefd1-c586-4d6c-81bf-460eb5499e2f",
   "metadata": {},
   "source": [
    "Or, just combine the `input` function and the `int()` function together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "227f6cf5-469c-44ec-a8bb-36084bb09801",
   "metadata": {
    "tags": [
     "skip-execution"
    ]
   },
   "outputs": [],
   "source": [
    "age = int(input(\"Enter your age: \"))      ### Directly convert input to integer\n",
    "\n",
    "print(type(age))\n",
    "\n",
    "print(f\"You are {age} years old.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-float-str-md",
   "metadata": {},
   "source": [
    "The `int()` function is not the only conversion function. Use `float()` when the text holds a decimal number, such as a price. Use `str()` to turn a number into text, for example when you want to join it to other strings with `+`. Recall that `\"I am \" + 25` raised a `TypeError` earlier; converting the number with `str()` fixes that."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-float-str-idx",
   "metadata": {},
   "source": [
    "```{index} float(), str()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-float-str-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "39.98\n",
      "I am 25 years old\n"
     ]
    }
   ],
   "source": [
    "price_text = \"19.99\"                         ### text typed by a user\n",
    "price = float(price_text)                    ### convert decimal text to a float\n",
    "print(price * 2)\n",
    "\n",
    "age = 25\n",
    "message = \"I am \" + str(age) + \" years old\"  ### convert the number to text before joining\n",
    "print(message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "d4b7690c",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Convert text input to numbers\n",
    "# input() returns text, so numeric input usually needs conversion.\n",
    "# The variables below simulate text a user typed into input().\n",
    "# Convert banana_count_text to an integer named banana_count.\n",
    "# Convert banana_price_text to a float named banana_price.\n",
    "# Calculate total_cost as banana_count * banana_price, rounded to 2 decimal places.\n",
    "# Print banana_count, then total_cost.\n",
    "banana_count_text = \"8\"\n",
    "banana_price_text = \"0.35\"\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd2ae61d",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n",
      "2.8"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "banana_count_text = \"8\"\n",
    "banana_price_text = \"0.35\"\n",
    "\n",
    "banana_count = int(banana_count_text)\n",
    "banana_price = float(banana_price_text)\n",
    "total_cost = round(banana_count * banana_price, 2)\n",
    "\n",
    "print(banana_count)\n",
    "print(total_cost)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63adcbbb",
   "metadata": {},
   "source": [
    "## Comments\n",
    "\n",
    "**Comments** are explanatory notes in your code that are ignored by the Python interpreter. Comments are used to: \n",
    "\n",
    "1. Explain complex logic: help others (and your future self) understand what the code does.\n",
    "2. Document assumptions: note why certain decisions were made.\n",
    "3. Mark **TODO** items: indicate areas that need improvement or completion.\n",
    "4. <span style=\"color: darkred\">**Disable code temporarily**</span>: comment out code for testing without deleting it.\n",
    "\n",
    "Single-line comments start with the hash symbol `#`. Everything after `#` on that line is ignored by Python. For multi-line comments, we use multiple hashes. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fdd8a0a",
   "metadata": {},
   "source": [
    "```{index} comment\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "a9a51b86",
   "metadata": {},
   "outputs": [],
   "source": [
    "### single-line comments\n",
    "# This is a comment explaining the code below\n",
    "price = 100\n",
    "tax_rate = 0.08  # 8% sales tax\n",
    "\n",
    "### multiple-line comments\n",
    "# Calculate total price including tax\n",
    "# total = price * (1 + tax_rate)\n",
    "# print(f\"Total price: ${total}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91633f0a",
   "metadata": {},
   "source": [
    "Ideally, good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff. For example, `velocity_mph = 8` might be clear without a comment, but `v = 8 # velocity in miles per hour` might be more readable in a mathematical formula."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d56e671d",
   "metadata": {},
   "source": [
    "### Docstring\n",
    "\n",
    "Unlike comments, which are ignored by the Python interpreter at runtime, docstrings are string literals used for documentation. They are processed by the interpreter and can be accessed with `__doc__` or `help()` as part of the program.\n",
    "\n",
    "Usually, a **docstring** is a string literal written as the first statement inside a module, function, class, or method to describe what it does, its inputs, outputs, or behavior. By convention it uses triple quotes (`\"\"\"...\"\"\"`) so it can span multiple lines. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6680ec33",
   "metadata": {},
   "source": [
    "```{index} docstring\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a612cb9b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "28.27431\n",
      "Return the area of a circle given its radius.\n"
     ]
    }
   ],
   "source": [
    "def area_circle(radius):\n",
    "    \"\"\"Return the area of a circle given its radius.\"\"\"\n",
    "    return 3.14159 * radius**2\n",
    "\n",
    "print(area_circle(3))      # 28.27431\n",
    "print(area_circle.__doc__) # Return the area of a circle given its radius."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "e4abdbdb",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "None\n",
      "18.6\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Add a useful docstring\n",
    "# The function below is already written for you, so you do not write def or return yourself.\n",
    "# 1. Replace the line \"# docstring goes here\" with a one-line docstring in triple quotes\n",
    "#    that says what the function returns.\n",
    "# 2. Add a short # comment at the end of the return line that explains the calculation.\n",
    "# 3. Run the cell. The last two lines print the docstring with __doc__ and call the function.\n",
    "def pages_per_day(total_pages, days):\n",
    "    ### Your code starts here.\n",
    "    # docstring goes here\n",
    "    return total_pages / days\n",
    "    ### Your code ends here.\n",
    "\n",
    "print(pages_per_day.__doc__)\n",
    "print(pages_per_day(93, 5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "f43d71b5",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Return the average number of pages read per day.\n",
      "18.6\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "def pages_per_day(total_pages, days):\n",
    "    \"\"\"Return the average number of pages read per day.\"\"\"\n",
    "    return total_pages / days    # total pages divided by the number of days\n",
    "\n",
    "print(pages_per_day.__doc__)\n",
    "print(pages_per_day(93, 5))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be293eb7-18ee-4a7a-ab53-38ebda3e3d05",
   "metadata": {},
   "source": [
    "## Built-in Functions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-be293eb7-18ee-4a7a-a",
   "metadata": {},
   "source": [
    "```{index} built-in function\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f44ee06-cfe1-48ab-b457-dd1c77ebe805",
   "metadata": {},
   "source": [
    "In Python, **built-in** functions and built-in modules are both part of the standard tools the language gives you, but they serve different purposes. Built-in functions are ready to use without requiring any imports. They are automatically available in every Python program. Examples of built-in functions include `print()` and `len()`. \n",
    "\n",
    "For the functionalities that Python does not provide, you either:\n",
    "1. Find a third-party **module** or **package** (or library) with the functions, install the package, and use the contained functions, or\n",
    "2. Write a **user-defined** custom function or class method.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efed9519-e9ba-4084-aab8-4b2fdf04097f",
   "metadata": {},
   "source": [
    "The [built-in functions](https://docs.python.org/3/library/functions.html) are available **without `import`**. The table below lists a compact working set for Python programs.\n",
    "\n",
    "| Function | Purpose |\n",
    "|---|---|\n",
    "| `print()` | display output |\n",
    "| `type()` | inspect an object's type |\n",
    "| `len()` | count items in a sequence or collection |\n",
    "| `round()` | round a number |\n",
    "| `abs()` | absolute value |\n",
    "| `min()`, `max()` | smallest or largest value |\n",
    "| `sum()` | add numeric values |\n",
    "| `sorted()` | return a sorted list |\n",
    "| `input()` | read text from a user in interactive programs |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "568a542a-195c-44dc-a990-5b805a5c59dd",
   "metadata": {},
   "source": [
    "As an example, you can apply functions on a Python list called scores like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "58ba3a78-0b60-4715-a77c-2773a36c7d17",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "75 100\n",
      "87.6\n",
      "[75, 83, 88, 92, 100]\n"
     ]
    }
   ],
   "source": [
    "scores = [88, 92, 75, 100, 83]\n",
    "print(len(scores))\n",
    "print(min(scores), max(scores))\n",
    "print(sum(scores) / len(scores))\n",
    "print(sorted(scores))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9facd021",
   "metadata": {},
   "source": [
    ":::{admonition} All 71 built-in functions\n",
    ":class: dropdown\n",
    "\n",
    "There are **71** built-in functions in recent Python 3 releases. The [Python documentation](https://docs.python.org/3/library/functions.html#built-in-functions) lists them all.\n",
    "\n",
    "```{figure} ../../figures/python-builtin-functions.png\n",
    "---\n",
    "width: 400px\n",
    "name: python-builtin-functions\n",
    "---\n",
    "Python built-in functions, from the [Python documentation](https://docs.python.org/3/library/functions.html). © Python Software Foundation, used under the [PSF License](https://docs.python.org/3/license.html).\n",
    "```\n",
    "\n",
    "The same functions grouped by purpose:\n",
    "\n",
    "| # | Group             | Functions          | Notes                  | \n",
    "|-| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |\n",
    "|1| Numbers & math                  | `abs`, `divmod`, `max`, `min`, `pow`, `round`, `sum`                                                                               | `pow(a, b, mod=None)` supports modular exponentiation.           |\n",
    "|2| Type construction/conversion | **`bool`**, **`int`**, **`float`**, `complex`, **`str`**, `bytes`, `bytearray`, `memoryview`, **`list`**, **`tuple`**, `set`, `frozenset`, **`dict`**, **`range`** | Convert or construct core types.                                 |\n",
    "|3| Object/attribute introspection  | **`type`**, **`isinstance`**, `issubclass`, **`id`**, `hash`, `dir`, `vars`, `repr`, `ascii`                                                   | `vars(obj)` → `obj.__dict__` when available.                     |\n",
    "|4| Attribute access                | `getattr`, `setattr`, `delattr`, `hasattr`                                                                                         | Dynamic attribute management.                                    |\n",
    "|5| Iteration & functional tools    | `iter`, `next`, **`enumerate`**, `zip`, `map`, `filter`, `sorted`, `reversed`                                                          | Prefer comprehensions when clearer.                              |\n",
    "|6| Sequence/char helpers           | **`len`**, `ord`, `chr`, `slice`                                                                                                       | `len()` works on many containers.                                |\n",
    "|7| I/O                             | **`print`**, **`input`**, `open`                                                                                                           | `open` returns a context manager; prefer `with open(...) as f:`. |\n",
    "|8| Formatting / representation     | `format`, `bin`, `oct`, `hex`                                                                                                      | Also see f-strings for formatting.                               |\n",
    "|9| Object model (OOP helpers)      | `object`, `property`, `classmethod`, `staticmethod`, `super`                                                                       | Define descriptors and class behaviors.                          |\n",
    "|10| Execution / metaprogramming     | `compile`, `eval`, `exec`                                                                                                          | Use with care; security concerns for untrusted input.            |\n",
    "|11| Environment / namespaces        | `globals`, `locals`                                                                                                                | Introspection of current namespaces.                             |\n",
    "|12| Help/debugging                  | `help`, `breakpoint`                                                                                                               | `breakpoint()` respects `PYTHONBREAKPOINT`.                      |\n",
    "|13| Import                          | `__import__`                                                                                                                       | Low-level import; usually use `import` statement instead.        |\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1f19663-b038-452a-8948-823590701944",
   "metadata": {},
   "source": [
    "Some functions return values you can store and reuse, while `print()` displays output but returns `None`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "ecfa7f73-24f8-4647-bcc6-e433fd875355",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "display only\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "return_value = print(\"display only\")\n",
    "print(return_value)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34a8dfc0-c6fe-4b13-a40e-585cb66a564a",
   "metadata": {},
   "source": [
    "\n",
    "```{index} argument\n",
    "```\n",
    "\n",
    "### Arguments\n",
    "\n",
    "When you call a function, the expressions inside the parentheses are called **arguments**. A function may take no argument or more than one argument. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "c1f4903f-029b-4ea4-b214-2b69eac489cf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "101\n",
      "5\n",
      "1.23 round to 2 places\n",
      "\n"
     ]
    }
   ],
   "source": [
    "num1 = int('101')           ### take one argument; string to integer\n",
    "num2 = int('101', 2)        ### take two argument; convert base 2 to int\n",
    "num3 = round(1.2345, 2)     ### 2 arg; round to two decimal places\n",
    "\n",
    "print(num1)\n",
    "print(num2)\n",
    "print(num3, 'round to 2 places')     ### two arguments\n",
    "\n",
    "print()                     ### no argument"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1383046",
   "metadata": {},
   "source": [
    "Arguments can be passed by position or by name. A **positional argument** is matched to a parameter by its place in the call. A **keyword argument** is written as `name=value` and is matched by name. Many built-in functions take optional parameters as keyword arguments, such as `sep` and `end` for `print()` or `reverse` for `sorted()`. To see a function's parameters, call `help()` on it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fb7e4e5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[75, 83, 88, 92, 100]\n",
      "[100, 92, 88, 83, 75]\n",
      "3.14\n"
     ]
    }
   ],
   "source": [
    "scores = [88, 92, 75, 100, 83]\n",
    "print(sorted(scores))                  ### positional argument only\n",
    "print(sorted(scores, reverse=True))    ### keyword argument\n",
    "print(round(3.14159, ndigits=2))       ### keyword argument; same as round(3.14159, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05ea9e2d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function round in module builtins:\n",
      "\n",
      "round(number, ndigits=None)\n",
      "    Round a number to a given precision in decimal digits.\n",
      "\n",
      "    The return value is an integer if ndigits is omitted or None.\n",
      "    Otherwise the return value has the same type as the number.  ndigits\n",
      "    may be negative.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(round)                            ### describes round() and its parameters"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e9e4d0c-a025-4e08-bd77-ee645d457143",
   "metadata": {},
   "source": [
    "### Return Values\n",
    "\n",
    "When you call built-in functions such as `abs()`, `round()`, `pow()`, and `len()`, they return a value you can assign to a variable or use as part of an expression. \n",
    "\n",
    "You use the `print()` function to display values, but it doesn't return values that you can assign to variables or use in expressions. So, `print()` "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-3e9e4d0c-a025-4e08-b",
   "metadata": {},
   "source": [
    "```{index} return value, None\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28455235-77c5-4f43-9274-5f3a58605c7e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7.5"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "abs(-7.5)                          ### returns a value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "422de389-8e0d-4a6a-ba02-386361296eec",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "87.6"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "average = round(sum(scores) / len(scores), 1)    ### assign the return value to a variable\n",
    "average                                         ### evaluate variable"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e39c70b-2fe9-42e6-895b-920dc004db1a",
   "metadata": {},
   "source": [
    "If a function doesn't have a `return` statement, it returns **`None`**, which is a special value like `True` and `False`. \n",
    "\n",
    "For example, you have used the `print` function to display strings, but it does not use a `return` statement to return a value. If we assign the result of a print statement to a variable, the variable will have the value of `None`.\n",
    "\n",
    "The example below still shows the output of the `print ()` statement first, though, even when it's been assigned. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "1f07a560-57f1-49fa-81cb-529cdec08de9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a string\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "unknown = print('a string')\n",
    "print(unknown)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-builtin-ex",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Summarize prices with built-in functions\n",
    "# The list below holds the prices of five fruits in dollars.\n",
    "# Use built-in functions to store the number of prices in count,\n",
    "# the lowest and highest prices in lowest and highest,\n",
    "# and the average price rounded to 2 decimal places in average.\n",
    "# Print count, then lowest and highest on one line, then average.\n",
    "prices = [1.25, 0.5, 2.75, 3.1, 0.89]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-builtin-ex-answer",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "5\n0.5 3.1\n1.7\n"
    }
   ],
   "source": [
    "### Solution\n",
    "prices = [1.25, 0.5, 2.75, 3.1, 0.89]\n",
    "\n",
    "count = len(prices)\n",
    "lowest = min(prices)\n",
    "highest = max(prices)\n",
    "average = round(sum(prices) / len(prices), 2)\n",
    "\n",
    "print(count)\n",
    "print(lowest, highest)\n",
    "print(average)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "272668d5-5ede-4d0a-8cec-71134ad1c8af",
   "metadata": {},
   "source": [
    "## Objects\n",
    "\n",
    "Every value in Python, whether it is a number, a string, or a function, is an **object**. An object is a piece of data stored in memory, and every object has three properties:\n",
    "\n",
    "- a **type**, which says what kind of value it is and what you can do with it,\n",
    "- a **value**, which is the data itself, and\n",
    "- an **identity**, which tells it apart from every other object while the program runs.\n",
    "\n",
    "A variable is a name that refers to an object."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2610f466",
   "metadata": {},
   "source": [
    "```{index} object\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cde537c0",
   "metadata": {},
   "source": [
    "Two built-in functions let you inspect an object. `type()` returns the object's type, and `id()` returns its identity as an integer. You can think of the identity as the object's address in memory. The number changes each time you run the program, so do not rely on a particular value. Section 2.1 looks at objects and identity in more detail."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "444876ad",
   "metadata": {},
   "source": [
    "```{index} object ID, id()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "7b2f8bae",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "<class 'int'>\n",
      "95\n",
      "4351290312\n"
     ]
    }
   ],
   "source": [
    "score = 95\n",
    "print(type(score))     ### the type: int\n",
    "print(score)           ### the value: 95\n",
    "print(id(score))       ### the identity: an integer that is unique while the object exists"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "855e25c4",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Inspect object information\n",
    "# Use the value below to inspect an object.\n",
    "# Print its type, value, and identity with type(), the variable itself, and id().\n",
    "value = \"Python\"\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "058627cb",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n",
      "Python\n",
      "4392214352\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "value = \"Python\"\n",
    "\n",
    "print(type(value))\n",
    "print(value)\n",
    "print(id(value))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5a1124b-57e2-49ee-81cf-7c18da972ec1",
   "metadata": {},
   "source": [
    "## Modules and Packages\n",
    "\n",
    "In Python, functions, classes, modules, packages, and libraries are essential tools for organizing and reusing code. In contrast to built-in functions, you need to use the `import` keyword to import the module before you use it.\n",
    "\n",
    "| Term | What It Is | Typical Use |\n",
    "|---|---|---|\n",
    "| Function | A named, reusable block of code that performs one specific task and can be called multiple times. | Break problems into smaller steps and avoid repeating logic. |\n",
    "| Class | A blueprint for creating objects that bundle data (attributes) and behavior (methods). | Model real-world entities and organize related state + behavior. |\n",
    "| Module | A single Python file (`.py`) containing code such as functions, classes, and variables. | Split code into files and **import** what you need. |\n",
    "| Package | A directory of related modules (and often subpackages) that forms a larger namespace. | Organize multi-file projects into clear components. |\n",
    "| Library | A broader collection of packages/modules built to solve common domains or tasks. | Reuse mature tools (e.g., data analysis, web, scientific computing) instead of building from scratch. |\n",
    "\n",
    "Together, these components help make Python code more organized, efficient, and maintainable. The most important distinction for now is:\n",
    "\n",
    "- **Module**: a single Python file (e.g., `mymodule.py`).\n",
    "- **Package**: a directory of modules (optionally with `__init__.py`)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0aa0f297",
   "metadata": {},
   "source": [
    "```{index} module, package, library\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e733b3b7",
   "metadata": {},
   "source": [
    "### Importing Modules"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81887816",
   "metadata": {},
   "source": [
    "```{index} import statement\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c9a5a08-a1c6-445d-85a3-45334cae58c9",
   "metadata": {},
   "source": [
    "Python ships with about 300 built-in and standard-library modules. For those modules, you can import them directly and use them (for example, `import math`). There are different ways of importing:\n",
    "\n",
    "| Import Pattern            | Example Code           | Usage Example         | Description                                 |\n",
    "|--------------------------|-----------------------|----------------------|---------------------------------------------|\n",
    "| Standard import          | `import math`         | `math.sqrt(25)`      | Clear, namespaced imports                   |\n",
    "| Aliased import           | `import math as m`    | `m.pi`               | Alias for brevity (common with large libs)  |\n",
    "| Selective import         | `from math import sqrt`| `sqrt(25)`           | Convenient, but use sparingly for readability|\n",
    "| Import all (not recommended) | `from math import *` | `sqrt(25)`           | Imports all names; can cause name conflicts and is discouraged |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3821d11c",
   "metadata": {},
   "source": [
    "**Style notes:**\n",
    "\n",
    "- Put `import` statements at the top of a file, one per line, so a reader sees at once what the program depends on.\n",
    "- Group them in this order, with a blank line between groups, as PEP 8 (Python's official style guide) recommends: the standard library, then third-party packages installed with `pip`, then your own modules.\n",
    "- Prefer **absolute imports**, which name a module from the top level, such as `import math` or `from statistics import mean`. A **relative import**, such as `from . import helpers`, names a module by where it sits next to the current file. It works only inside a package (a folder of modules), where the package's authors use it to import their own files. You will not need it in this book.\n",
    "\n",
    "```python\n",
    "import math                    # standard library\n",
    "import numpy as np             # third-party package\n",
    "from shared import download    # your own module\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40bd4944-4391-486e-aa72-7034ed292a83",
   "metadata": {},
   "source": [
    "To use methods or attributes from a module, use the **dot operator** (`.`) between the module name and the attribute name. For example, the Python `math` module provides a variable called `pi` that contains the mathematical constant denoted $\\pi$. We can access it as `math.pi`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "c7f6c1f3-fc38-40eb-a709-6ed0e5e05426",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.0"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "math.sqrt(25)     ### dot operator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "946a97d7",
   "metadata": {},
   "source": [
    "The standard library has a module for most everyday jobs. The three examples below each use a different import pattern from the table above. `statistics` summarizes numbers, `datetime` works with dates, and `json` converts data to the text format that web services exchange."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "244d42cc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "87.6\n",
      "88"
     ]
    }
   ],
   "source": [
    "from statistics import mean, median     ### selective import: no module name needed\n",
    "scores = [88, 92, 75, 100, 83]\n",
    "print(mean(scores))\n",
    "print(median(scores))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ae1d6d4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Monday, November 02, 2026\n",
      "53"
     ]
    }
   ],
   "source": [
    "import datetime as dt                   ### aliased import: dt is a shorter name\n",
    "exam = dt.date(2026, 11, 2)\n",
    "print(exam.strftime(\"%A, %B %d, %Y\"))\n",
    "print((dt.date(2026, 12, 25) - exam).days)    ### days between two dates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccdbfb4d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"fruit\": \"apple\", \"price\": 1.25}"
     ]
    }
   ],
   "source": [
    "import json                             ### standard import: json.dumps(...)\n",
    "record = {\"fruit\": \"apple\", \"price\": 1.25}\n",
    "print(json.dumps(record))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "639e10b1",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Import a module and use dot notation\n",
    "# Import math.\n",
    "# Store the square root of 144 in root_value.\n",
    "# Store the area of a circle with radius 3 in circle_area.\n",
    "# Print root_value and round(circle_area, 2).\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "e98bfdec",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12.0\n",
      "28.27\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import math\n",
    "\n",
    "root_value = math.sqrt(144)\n",
    "circle_area = math.pi * 3 ** 2\n",
    "\n",
    "print(root_value)\n",
    "print(round(circle_area, 2))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1208a0a-c571-4d4b-9fdc-64aadce486ef",
   "metadata": {},
   "source": [
    "### Installing Packages\n",
    "\n",
    "External, third-party modules are created by the Python community. You must use `pip` to install them first (for example, notebook, NumPy, or pandas), then import them before using them. Most software on the Python Package Index (PyPI; https://pypi.org, where `pip` finds software packages) is referred to as \"packages\" in this context.\n",
    "\n",
    "To install the packages in the CLI, you would go into your project directory, activate your virtual environment, and then use the `pip` installation syntax to install the package into your `.venv` folder (site-packages) for dependency integrity: \n",
    "\n",
    "`pip install [package_name]` \n",
    "\n",
    "If you are in Jupyter Notebook, use the Jupyter Notebook magic command `%pip` (instead of the older `!pip`) to install the package into the active kernel:\n",
    "\n",
    "`%pip install [package_name]` "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-e1208a0a-c571-4d4b-9",
   "metadata": {},
   "source": [
    "```{index} pip, PyPI\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac740e54-5362-4127-9971-6307d3516a4e",
   "metadata": {},
   "source": [
    "For example, NumPy (numeric Python) is a popular package for data science. From inside Jupyter Notebook, you can install it with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "e4acd236-f2c2-4456-b107-97889508eb22",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: numpy in /Users/tychen/workspace/py/.venv/lib/python3.13/site-packages (2.3.4)\n",
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m25.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m26.2.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "%pip install numpy"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d688a290",
   "metadata": {},
   "source": [
    "You probably want to comment the `%pip install` line out after installation as you only need to install it once in the virtual environment. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0892cb9-dd30-4b8b-a181-520f2ecc7766",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "```{index} keywords\n",
    "```\n",
    "## Keywords \n",
    "\n",
    "Python reserved words, or keywords, are words that you are not supposed to use for variable names.\n",
    "\n",
    "Reserved words, or keywords, are special words reserved by the programming language to be used to specify the **structure** of a program. Keywords of the language cannot be used as ordinary identifiers (such as variable names). \n",
    "\n",
    "For example, if you try to assign a string to a variable named _class_, you will receive a syntax error because `class` is a **keyword**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "b1d91af3-1b34-4d1c-bb95-d676c1ddc11b",
   "metadata": {
    "language": "markdown",
    "mystnb": {
     "error_lexer": "text"
    }
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (454198755.py, line 1)",
     "output_type": "error",
     "traceback": [
      "  \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[37]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[31m    \u001b[39m\u001b[31mclass = 'Assigning a string to a keyword to be a variable name...'\u001b[39m\n          ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "%%expect SyntaxError\n",
    "class = 'Assigning a string to a keyword to be a variable name...'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84971843",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "Here's a complete list of [35 Python keywords](https://docs.python.org/3/reference/lexical_analysis.html#keywords) as shown in the [Python Language Reference](https://docs.python.org/3.13/reference/index.html):\n",
    "```\n",
    "False      await      else       import     pass\n",
    "None       break      except     in         raise\n",
    "True       class      finally    is         return\n",
    "and        continue   for        lambda     try\n",
    "as         def        from       nonlocal   while\n",
    "assert     del        global     not        with\n",
    "async      elif       if         or         yield\n",
    "```\n",
    "\n",
    "Keywords are part of Python's syntax. Instead of memorizing all 35 at once, it helps to group some common ones by the jobs they do:\n",
    "\n",
    "| Category | Examples |\n",
    "|---|---|\n",
    "| Flow control | `if`, `elif`, `else`, `for`, `while`, `break`, `continue`, `pass` |\n",
    "| Definitions | `def`, `class`, `lambda` |\n",
    "| Boolean logic and identity | `and`, `or`, `not`, `is`, `in`, `True`, `False`, `None` |\n",
    "| Imports and scope | `import`, `from`, `global`, `nonlocal` |\n",
    "| Exceptions and context | `try`, `except`, `finally`, `raise`, `assert`, `with`, `as` |\n",
    "| Async and generators | `async`, `await`, `yield` |\n",
    "\n",
    "In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, the editor or interpreter will warn you."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9a70e08",
   "metadata": {},
   "source": [
    "To show all the Python keywords, you can do:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "e3a4d631-e359-48ac-a70c-b54f749d57b7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of Python keywords: 35 \n",
      "\n",
      "All Python keywords: \n",
      " ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n"
     ]
    }
   ],
   "source": [
    "from keyword import kwlist\n",
    "print(\"Number of Python keywords:\", len(kwlist), \"\\n\")\n",
    "print(\"All Python keywords: \\n\", kwlist)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0118475",
   "metadata": {},
   "source": [
    "As stated earlier, keywords form the **program structure**. The examples below show how keywords act like the grammatical parts of a program.\n",
    "\n",
    "For example, `if` is a keyword in Python and is highlighted in most code editors.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "ff996be3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Positive number\n"
     ]
    }
   ],
   "source": [
    "### example of the \"if\" keyword in Python\n",
    "num = 5\n",
    "if num > 0:\n",
    "    print(\"Positive number\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e33caaf9",
   "metadata": {},
   "source": [
    "And `for` and `in` are also keywords."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "a738778c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1 2 3 4 "
     ]
    }
   ],
   "source": [
    "### example of the \"for\" keyword in Python\n",
    "for i in range(5):\n",
    "    print(i, end=\" \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "807bdb9f",
   "metadata": {},
   "source": [
    "### Soft Keywords\n",
    "\n",
    "Python's soft keywords are special words that act as keywords only in specific contexts, but can be used as regular identifiers (such as variable or function names) in other contexts. As of Python 3.12, there are four [soft keywords](https://docs.python.org/3.13/reference/lexical_analysis.html#soft-keywords): **match**, **case**, **_**, and **type**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a181b69",
   "metadata": {},
   "source": [
    "```{index} soft keyword\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "ff7c0f38",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Check keywords\n",
    "# Import the keyword module.\n",
    "# Store whether \"class\" is a Python keyword in class_is_keyword.\n",
    "# Store whether \"dataset\" is a Python keyword in dataset_is_keyword.\n",
    "# Print both values.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "0a02c9e7",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import keyword\n",
    "\n",
    "class_is_keyword = keyword.iskeyword(\"class\")\n",
    "dataset_is_keyword = keyword.iskeyword(\"dataset\")\n",
    "\n",
    "print(class_is_keyword)\n",
    "print(dataset_is_keyword)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "517eb3c9",
   "metadata": {},
   "source": [
    "```{index} error message, traceback, error type\n",
    "```\n",
    "\n",
    "## Reading Error Messages\n",
    "\n",
    "When Python cannot run your code, it stops and prints an **error message**. The message can look long, but the most useful part is the last line: it names the **error type** and says what went wrong. Read the last line first, then look at the line number above it. The longer report above the last line is called a **traceback**; it lists the lines Python was running when the error occurred.\n",
    "\n",
    "| Error Type | What It Means | Typical Cause |\n",
    "|---|---|---|\n",
    "| `SyntaxError` | The code breaks Python's grammar, so it cannot start | A missing colon, quote, or parenthesis |\n",
    "| `IndentationError` | A kind of `SyntaxError` for incorrect indentation | A block with no indented lines |\n",
    "| `NameError` | Python does not know the name | A misspelled variable, or a variable used before it is assigned |\n",
    "| `TypeError` | An operation is applied to the wrong type | `\"Total: \" + 25` |\n",
    "| `ValueError` | The type is right, but the value is not usable | `int(\"abc\")` |\n",
    "\n",
    "Each cell below raises an error on purpose. Find the error type on the last line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ae442cc",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'totl_price' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[31mNameError\u001b[39m\u001b[31m:\u001b[39m name 'totl_price' is not defined\n"
     ]
    }
   ],
   "source": [
    "%%expect NameError\n",
    "\n",
    "total_price = 10\n",
    "print(totl_price)           ### misspelled name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48dce512",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (3866156273.py, line 1)",
     "output_type": "error",
     "traceback": [
      "  \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[9]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[31m    \u001b[39m\u001b[31mif 5 > 3 print(\"yes\")       ### missing colon\u001b[39m\n             ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "%%expect SyntaxError\n",
    "\n",
    "if 5 > 3 print(\"yes\")       ### missing colon"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4bb3c582",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "invalid literal for int() with base 10: 'abc'",
     "output_type": "error",
     "traceback": [
      "\u001b[31mValueError\u001b[39m\u001b[31m:\u001b[39m invalid literal for int() with base 10: 'abc'\n"
     ]
    }
   ],
   "source": [
    "%%expect ValueError\n",
    "\n",
    "int(\"abc\")                  ### text that is not a number"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2fe9c8e",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Identify error types\n",
    "# Each line below would raise an error if you ran it.\n",
    "# Set each variable to the error type it raises:\n",
    "# \"SyntaxError\", \"NameError\", \"TypeError\", or \"ValueError\".\n",
    "# 1: print(total)               (total was never assigned)\n",
    "# 2: print(\"Total: \" + 25)\n",
    "# 3: if 5 > 3 print(\"yes\")\n",
    "# 4: int(\"12.5\")\n",
    "### Your code starts here.\n",
    "error_1 = \"\"\n",
    "error_2 = \"\"\n",
    "error_3 = \"\"\n",
    "error_4 = \"\"\n",
    "### Your code ends here.\n",
    "print(error_1, error_2, error_3, error_4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c654ac1",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NameError TypeError SyntaxError ValueError\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "error_1 = \"NameError\"\n",
    "error_2 = \"TypeError\"\n",
    "error_3 = \"SyntaxError\"\n",
    "error_4 = \"ValueError\"\n",
    "print(error_1, error_2, error_3, error_4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "679af114",
   "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
}
