{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a14edb7e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "# On Programming"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "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\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbcab2fd",
   "metadata": {},
   "source": [
    "```{figure} ../../figures/python-pours-many-uses.svg\n",
    "---\n",
    "name: python-pours-many-uses\n",
    "width: 55%\n",
    "---\n",
    "Python is versatile. Adapted from [a post by Dvz (@PythonDvz) on X](https://x.com/PythonDvz/status/2009855471071739954), January 9, 2026 {cite}`dvz_2026`.[^python-kettle]\n",
    "```\n",
    "\n",
    "[^python-kettle]: This multi-spout kettle cartoon circulates in many versions, most of them AI-generated, so its creator is hard to trace. Our figure is redrawn from the version Dvz posted on X on January 9, 2026. The same image was shared later in a [Facebook group](https://www.facebook.com/groups/3950898038297989/posts/25957502133877597/) (February 23, 2026) and in a [LinkedIn post by Ilkay Gurel](https://www.linkedin.com/posts/ilkaygurel_sql-dataanalytics-dataengineering-share-7445584815875149824-tyez/) (April 3, 2026). A possible original is the \"multi-spout kettle\" meme template on Supermeme.ai {cite}`supermeme_kettle`, whose image dates from October 2024."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9edc9c19",
   "metadata": {},
   "source": [
    "Learning programming is largely about **connecting the dots**. First, you need enough concepts, examples, and practice problems to work with. Then you need to connect them so they become usable knowledge.\n",
    "\n",
    "Two habits matter early:\n",
    "\n",
    "1. **Repeat**: Keep collecting and revisiting the core ideas.\n",
    "2. **Associate**: Keep linking new ideas to the ideas you already have.\n",
    "\n",
    "```{figure} ../../figures/knowledge-experience-creativity.svg\n",
    ":name: experience-knowledge-creativity\n",
    ":width: 80%\n",
    ":align: center\n",
    "\n",
    "Knowledge, experience, and creativity. Adapted from a cartoon [shared by TEDxGateway](https://www.facebook.com/TEDxGateway/photos/knowledge-vs-experience-vs-creativitybased-on-original-art-by-gapingvoid/627069164013335/), based on original art by [gapingvoid](https://www.gapingvoid.com/).\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84d40dc2",
   "metadata": {},
   "source": [
    "Becoming fluent in Python requires a working knowledge of several connected ideas. Some of the essential concepts include:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20eae5a1",
   "metadata": {},
   "source": [
    "<iframe width=\"560\" height=\"315\"\n",
    "src=\"https://www.youtube-nocookie.com/embed/-uleG_Vecis\"\n",
    "  frameborder=\"0\"\n",
    "  allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\"\n",
    "  allowfullscreen\n",
    "  referrerpolicy=\"strict-origin-when-cross-origin\"></iframe>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1992a705",
   "metadata": {},
   "source": [
    "This chapter introduces fundamental programming concepts using Python as the teaching language. These ideas form the foundation for the programming skills you will build throughout the course:\n",
    "\n",
    "1. **Algorithms and Programs**\n",
    "2. **Programming Language**\n",
    "3. **Levels of Abstraction**\n",
    "4. **Interpreted vs Compiled**\n",
    "5. **Programming Constructs**\n",
    "6. **Expressions and Statements**\n",
    "7. **Programming Paradigms**\n",
    "8. **Number Systems**\n",
    "9. **Resources**\n",
    "\n",
    "This chapter focuses on the **constructs** of programming. This vocabulary matters because you will use it to understand computational material, design solutions to computational problems, and communicate clearly with other programmers. These concepts appear in most programming languages, even when the syntax and implementation details differ. Learning them now will give you a stronger foundation for studying other languages and tackling more advanced programming problems."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-algorithms",
   "metadata": {},
   "source": [
    "## Algorithms and Programs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-algorithms-index",
   "metadata": {},
   "source": [
    "```{index} algorithm, input and output\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-algorithms-def",
   "metadata": {},
   "source": [
    "Before you write any code, you need a plan for solving the problem. An **algorithm** is a finite, ordered set of unambiguous steps that turns some **input** into the desired **output**. Each step must be clear enough that anyone, or any machine, following it gets the same result, and the steps must eventually come to an end.\n",
    "\n",
    "An algorithm describes the **logic** of a solution, not the **syntax** of a particular language. You can write an algorithm in plain English, as a numbered list, or as a flowchart before you decide which programming language to use. A recipe is a familiar example: it takes ingredients as input, lists steps in a fixed order, and ends with a finished dish as output.\n",
    "\n",
    "For example, here is an algorithm for finding the largest number in a list:\n",
    "\n",
    "1. Look at the first number and remember it as the largest so far.\n",
    "2. Look at the next number. If it is greater than the largest so far, remember it instead.\n",
    "3. Repeat step 2 until no numbers are left.\n",
    "4. Report the number you remembered.\n",
    "\n",
    "Given the input `[42, 17, 88, 63]`, the steps remember 42, keep 42 after seeing 17, switch to 88, keep 88 after seeing 63, and report `88` as the output."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-algorithms-program",
   "metadata": {},
   "source": [
    "A **program** is an algorithm written in a programming language so that a computer can execute it. The same algorithm can be implemented in Python, Java, or any other language; only the notation changes. The cell below implements the largest-number algorithm in Python. You will learn the `for` loop and the `if` statement it uses in Chapter 3. For now, notice how each line matches one of the steps above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-algorithms-example",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "88\n"
    }
   ],
   "source": [
    "### the largest-number algorithm implemented in Python\n",
    "numbers = [42, 17, 88, 63]\n",
    "\n",
    "largest = numbers[0]          # step 1: remember the first number\n",
    "for num in numbers[1:]:       # step 3: repeat for each remaining number\n",
    "    if num > largest:         # step 2: keep the larger number\n",
    "        largest = num\n",
    "print(largest)                # step 4: report the result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-algorithms-builtin",
   "metadata": {},
   "source": [
    "Python also provides a built-in function, `max()`, that carries out this algorithm for you: `max(numbers)` returns `88`. Built-in functions like `max()` are algorithms that other programmers have already implemented and tested, so you can reuse them instead of writing the steps yourself."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57e17231-1191-44ae-ad08-f6da39c8dbcb",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Programming Language\n",
    "\n",
    "Learning to program means learning a new way of thinking -- thinking like a computer scientist. This approach combines some of the best features of mathematics, engineering, and the natural sciences. Like mathematicians, computer scientists use formal languages to denote ideas -- specifically computations. Like engineers, they design things, assembling components into systems and evaluating trade-offs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.\n",
    "\n",
    "### Natural vs Formal Languages\n",
    "**Natural languages** are the languages that people use to communicate, such as English, Spanish, and French. They were not designed by people; they evolved naturally. **Formal languages** are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Similarly, programming languages are formal languages designed to express computations. Although formal and natural languages have some features in common, there are important differences:\n",
    "\n",
    "* Ambiguity: Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any program has exactly one meaning, regardless of context.\n",
    "\n",
    "* Redundancy: In order to make up for ambiguity and reduce misunderstandings, natural languages use redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.\n",
    "\n",
    "* Literalness: Natural languages are full of idiom and metaphor. Formal languages mean exactly what they say.\n",
    "\n",
    "Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. Formal languages are **denser** than natural languages, so it takes longer to read them. Additionally, the **structure** is important, so it is not always best to read from top to bottom or left to right. Finally, the **details** matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b36e5a95",
   "metadata": {},
   "source": [
    "```{index} programming language, natural language, formal language\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "333a6fc9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Levels of Abstraction\n",
    "Programming languages exist on a spectrum, ranging from those closest to hardware (machine code) to those closest to high-level languages that are more human-readable, as shown below: \n",
    "\n",
    "| Level | Description | Examples | Code Example |\n",
    "|-------|-------------|----------|--------------|\n",
    "| **High-Level Languages** | Closest to human language, abstracted from hardware details | Python, Java, JavaScript, C, C++ | `print(\"Hello, World!\")` |\n",
    "| **Low-Level Languages** | Closer to machine code, direct hardware manipulation | Assembly language | `mov eax, 1`<br>`msg db 'Hello, World!', 0xA` |\n",
    "| **Machine Code** | Binary instructions directly executed by CPU | Binary (0s and 1s) | `10110000 00000000`<br>`10110001 00001010` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4bd6488",
   "metadata": {},
   "source": [
    "```{index} abstraction, high-level language, low-level language\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dc3dcef",
   "metadata": {},
   "source": [
    "## Interpreted vs. Compiled \n",
    "\n",
    "Programming languages also differ in how they are executed. **Interpreted languages** such as Python, JavaScript, and Ruby are commonly run by an interpreter, which translates and executes code at runtime. **Compiled languages** such as C, C++, and Rust usually require a compilation step that translates source code into machine code before execution, which can improve runtime performance. Many modern languages use a hybrid approach: source code is compiled to intermediate **bytecode**, then interpreted or just-in-time compiled by a virtual machine."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ed404b1",
   "metadata": {},
   "source": [
    "```{index} interpreter, compiler, interpreted language, compiled language, bytecode\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a93588f-5092-451d-9886-931b0d18cf6c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Programming Constructs\n",
    "\n",
    "A computer program is a set of instructions written in the notation of a programming language. Although programs can become complex, most programming languages rely on a small set of core control structures:\n",
    "\n",
    "1. **Sequence**: instructions are executed one after another (sequential execution).\n",
    "2. **Selection**: decision-making/control structure; namely, choosing between alternative paths of actions within a program.\n",
    "3. **Iteration**: code repetition; either count-controlled or condition-controlled.\n",
    "\n",
    "Programming languages also provide supporting elements such as:\n",
    "\n",
    "1. **Subroutine**: blocks of code (**function**/**method**) in a modular program performing a particular task.\n",
    "2. **Nesting**: Selection and iteration constructs can be nested within each other.\n",
    "3. **Variable**: a named computer memory location that stores values\n",
    "4. Data type (**Type**): a classification of data values specifying the values and operations on the values.\n",
    "5. **Operator**: symbols that perform operations on one or more operands.\n",
    "6. **Array**: storing multiple values of the same data type in a single variable, aka, data **collections**."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7438347c",
   "metadata": {},
   "source": [
    "```{index} sequence, selection, iteration, subroutine, variable, operator\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a36bda14-db09-4307-b06d-73e084734235",
   "metadata": {},
   "source": [
    "```{index} expression, statement\n",
    "```\n",
    "## Expressions and Statements\n",
    "\n",
    "\n",
    "In programming languages, expressions and statements are fundamental building blocks for formulating and using the language. \n",
    "\n",
    "By definition, an **`expression`** is a combination of values, variables, operators, and function calls that the Python interpreter can **evaluate** to produce a **single value**, which may be assigned to a variable for later use. Note that a **single** literal value, like an integer or string, can be an expression. \n",
    "\n",
    "An expression may contain **operators** and **operands**, such as `a + b * c`, as shown below.\n",
    "\n",
    ":::{figure} ../../figures/expression-anatomy.svg\n",
    ":alt: The statement result = a + b * c with its variable, operands, and operators labeled\n",
    ":width: 60%\n",
    ":align: left\n",
    "\n",
    "Expression, Operand, and Operator\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a11981de-170f-4a7f-9660-cd1c87b2c529",
   "metadata": {},
   "source": [
    "For example, we can create a variable and it will an expression by itself. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "95361762-aeaf-41c9-aa53-bca331ce636b",
   "metadata": {},
   "outputs": [],
   "source": [
    "message = 'And now for something completely different'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79b86c35-38bc-41c7-8488-99dd046c0e01",
   "metadata": {},
   "source": [
    "A variable can be an expression, so we can display the value of `message` by asking Python to evaluate it to see the value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4c76abe5-e2eb-4c70-88c1-0e4da3a6481d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'And now for something completely different'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "message"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f50b6492",
   "metadata": {},
   "source": [
    "A **`statement`** is a complete instruction for the interpreter to **execute**. A statement performs an action or controls the flow of a program, but it does not produce a value that can be used elsewhere like an expression. For example, an *assignment statement* creates a variable and gives it a value, but the statement itself has no value.\n",
    "\n",
    "Computing the value of an expression is called **evaluation**; running a statement is called **execution**. A statement performs an action, while an expression **computes** a **value**. For example:\n",
    "\n",
    "| Type           | Example       | Description                                                         |\n",
    "| -------------- | ------------- | ------------------------------------------------------------------- |\n",
    "| **Statement**  | `x = 5`       | Assignment statement: Assigns 5 to `x` (changes program state). Produces **no value**.    |\n",
    "|                | `print(x)`    | Print statement: Prints something to the screen (has an effect); no value.           |\n",
    "|                | `if x > 0:`   | `if` statement: Begins a conditional block — a control flow structure; no value. |\n",
    "|                | `import math` | Imports the `math` module; no value. |\n",
    "| **Expression** | `2 + 3`       | Produces the value `5`.                                             |\n",
    "|                | `x * y`       | Computes a value based on `x` and `y`.                              |\n",
    "|                | `len(\"data\")` | Evaluates to `4`.                                                   |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d1a4b4d5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x is positive\n"
     ]
    }
   ],
   "source": [
    "x = 5                # statement: assigns a value; nothing is displayed\n",
    "x + 5                # expression: evaluates to 10, so the REPL/notebook shows 10\n",
    "if x > 0:            # statement: controls flow; no value, only the side effect below\n",
    "    print(\"x is positive\")   # a block of code that executes if the condition is true"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-paradigms-h",
   "metadata": {},
   "source": [
    "## Programming Paradigms\n",
    "\n",
    "A **programming paradigm** is a style of organizing a program and thinking about computation. Most beginners learn the **imperative paradigm** first, and it is the paradigm of Part I of this book.\n",
    "\n",
    "In the imperative paradigm, a program is a sequence of **commands** that tell the computer *how* to reach a result, step by step. The commands read and change the program's **state**, meaning the values currently stored in its variables. The constructs from the previous section are the imperative toolkit: sequence runs the steps in order, selection chooses between steps, iteration repeats steps, and assignment updates state.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-paradigms-index",
   "metadata": {},
   "source": [
    "```{index} programming paradigm, imperative programming, state\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-paradigms-ex",
   "metadata": {},
   "source": [
    "The cell below adds up a list of prices. It starts with a total of `0`, then visits each price and updates `total`. To follow the program, you track how the value of `total` changes after each statement."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-paradigms-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "13.75\n"
     ]
    }
   ],
   "source": [
    "### imperative style: a sequence of statements that update state\n",
    "prices = [4.50, 3.25, 6.00]\n",
    "total = 0\n",
    "for price in prices:\n",
    "    total = total + price      # each pass changes the state of total\n",
    "print(total)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-paradigms-after",
   "metadata": {},
   "source": [
    "Imperative code maps closely to how the computer executes instructions, so it is direct to write and to trace by hand. As programs grow, though, many statements changing shared state become hard to follow. Later paradigms respond to that problem:\n",
    "\n",
    "| Paradigm | Organizing idea | Where you meet it |\n",
    "|---|---|---|\n",
    "| **Imperative** | Commands that change state step by step | Part I (Chapters 1-5) |\n",
    "| **Object-oriented** | Objects that bundle state with the behavior that changes it | Chapter 9 |\n",
    "| **Functional** | Functions that turn inputs into outputs with fewer state changes | Chapter 10 |\n",
    "\n",
    "Python is **multi-paradigm**: you can mix all three styles in one program. This book starts with imperative code because the other styles build on it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-ai-h",
   "metadata": {},
   "source": [
    "## Programming in the Age of AI\n",
    "\n",
    "AI coding assistants such as ChatGPT, Claude, and GitHub Copilot can write working code from a plain-English request. That raises a fair question as you start this book: if AI can write the code, why learn to program?\n",
    "\n",
    "Writing code was never the whole job. A program also has to be correct, and someone has to decide whether it is. An assistant can produce code in seconds, but it cannot take responsibility for that code. You can, but only if you can read it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-ai-index",
   "metadata": {},
   "source": [
    "```{index} AI coding assistant, vibe coding\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-ai-fig",
   "metadata": {},
   "source": [
    "```{figure} ../../figures/fundamentals-vs-vibe-coding.svg\n",
    ":name: fundamentals-vs-vibe-coding\n",
    ":width: 100%\n",
    ":align: center\n",
    "\n",
    "Learning the fundamentals vs. skipping them. Adapted from [a post by Adnaan (@adnaannasir_) on X](https://x.com/adnaannasir_/status/2095368979309310090), September 2, 2026.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-ai-paths",
   "metadata": {},
   "source": [
    "{numref}`fundamentals-vs-vibe-coding` contrasts two paths. On the left, knowledge grows step by step as each topic builds on the one before it; the steps roughly follow the chapters of this book. The curve starts slowly, but it keeps rising and does not fall.\n",
    "\n",
    "On the right, a learner skips the fundamentals and relies on AI from day one. This style is often called **vibe coding**: describe what you want, accept whatever code comes back, and keep going as long as the program seems to run. Confidence climbs fast because the code appears to work. Notice the label on the vertical axis, though: it measures confidence, not skill. When the program fails in real use, the vibe coder has no way to find out why, because they never understood the code in the first place. Debugging code you cannot read is guessing."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-ai-why",
   "metadata": {},
   "source": [
    "The ideas in this chapter explain why reading code still matters. A request to an assistant is written in a natural language, which is ambiguous. The code that comes back is written in a formal language, which means exactly one thing (see Natural vs. Formal Languages above). The assistant has to guess which meaning you intended, and only someone who can read the code can tell whether it guessed right. Algorithms work the same way: if you cannot trace the steps of an algorithm yourself, you cannot tell whether a generated one handles every case.\n",
    "\n",
    "The lesson is not to avoid AI. It is to use AI on top of the fundamentals, not in place of them. A few habits help:\n",
    "\n",
    "- **Read every line** before you run it. If a line is unclear, ask the assistant to explain it, then check the explanation against the Python documentation.\n",
    "- **Predict, then run.** Decide what the code should print before you execute it. A surprise means that either the code or your understanding is wrong, and both are worth knowing.\n",
    "- **Test it** on inputs you choose, including edge cases such as an empty list or a zero. Chapter 5 covers testing.\n",
    "- **Keep requests small.** Ask for one function at a time, not a whole program, so you can review each change.\n",
    "- **Write it yourself first** when you are learning a new concept. The practice is the point, and an answer you did not work out teaches you little.\n",
    "\n",
    "For graded work, follow your course's policy on AI use."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f583efc",
   "metadata": {},
   "source": [
    "## Number Systems\n",
    "\n",
    "```{admonition} Advanced Topic\n",
    ":class: tip\n",
    "This section covers number systems (binary, octal, hexadecimal), which are more advanced. They are useful for understanding how computers work at a lower level, but they are not essential for writing most Python programs. Feel free to skim this section on first reading and return to it later when you need to work with different number bases.\n",
    "```\n",
    "\n",
    "<!-- TODO: add base 16 conversion -->\n",
    "\n",
    "In programming, number systems are ways of representing numbers using different bases. Computers store and process data in binary, but programmers often use other bases for convenience, readability, or hardware interaction. The four main number systems used in programming are binary (base-2), decimal (base-10), hexadecimal (base-16), and octal (base-8):\n",
    "\n",
    "| System          | Base | Digits Used | Typical Use                                                | Python Example (all = 100) |\n",
    "| --------------- | ---- | ----------- | ---------------------------------------------------------- | -------------------------- |\n",
    "| **Binary**      | 2    | 0–1         | Hardware, CPU, memory, bitwise operations                  | `0b1100100` → 100          |\n",
    "| **Octal**       | 8    | 0–7         | Unix file permissions | `0o144` → 100              |\n",
    "| **Decimal**     | 10   | 0–9         | Human-friendly math, user input/output                     | `100` → 100                |\n",
    "| **Hexadecimal** | 16   | 0–9, A–F    | Memory addresses, colors, debugging, networking     | `0x64` → 100               |\n",
    "\n",
    "As you can see, binary literals start with `0b`, octal literals start with `0o`, and hexadecimal literals start with `0x`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd0923ef",
   "metadata": {},
   "source": [
    "```{index} number systems, binary, octal, decimal, hexadecimal, base conversion\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e9c46ce",
   "metadata": {},
   "source": [
    "All number systems use **positional notation**, where each digit's value depends on its **position** and the number system's **base**. For example, the decimal number `345`, or `345 (base 10)`, can be represented as shown in the table below. Each digit represents a different power of the base and contributes a corresponding value.\n",
    "\n",
    "\n",
    "| digit | position | digit x base^position | expanded | value |\n",
    "|-------|----------|------------------------|----------|-------|\n",
    "| **3** | 2 | 3 × 10^2 | 3 × 100 | **300** |\n",
    "| **4** | 1 | 4 × 10^1 | 4 × 10 | **40** |\n",
    "| **5** | 0 | 5 × 10^0 | 5 × 1 | **5** |\n",
    "|       |   |   |        | **345** |\n",
    "\n",
    "Here, the digit `3` means `300` because it is in the hundreds place (`10^2`). Therefore:\n",
    "\n",
    "```\n",
    "digit value = digit x (base ^ position)\n",
    "```\n",
    "You then add all the digit values together to get the value of the number:\n",
    "```\n",
    "345 = 3×10² + 4×10¹ + 5×10⁰\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e80ed8f",
   "metadata": {},
   "source": [
    "Following the same process of adding up the digit values, we can convert `1011 (base 2)` to decimal like this:\n",
    "\n",
    "| Digit | Position | 2 to the *n*th Power | Value |\n",
    "| -------- | ---------- | ----- | ----- |\n",
    "| 1     | 3        | 2³         | 8     |\n",
    "| 0     | 2        | 2²         | 0     |\n",
    "| 1     | 1        | 2¹         | 2     |\n",
    "| 1     | 0        | 2⁰         | 1     |\n",
    "|       |          |            | 11    |\n",
    "\n",
    "\n",
    "So, we can do **base conversion** from base 2 to base 10 by adding the place values:\n",
    "```\n",
    "1011₂ = 1x2^3 + 0 x 2^2 + 1 x 2^1 + 1 x 2^0 = 8 + 2 + 1 = 11₁₀\n",
    "\n",
    "```\n",
    "\n",
    "Another way is to put the place values at the top:\n",
    "\n",
    "| Position  | 2^3 | 2^2 | 2^1 | 2^0 |    |\n",
    "|-- | --- | --- | --- | --- | -- | \n",
    "| Place value  | 8   |  4  |  2  |  1  |    |\n",
    "| Digit  | 1   |  0  |  1  |  1  |    |\n",
    "| Calculation  | 1×8 |  0×4 | 1×2 |  1×1   |\n",
    "| Value  | 8   |  0  |  2  |  1  | 11 |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3e37707",
   "metadata": {},
   "source": [
    "The base 2 system, or binary, is foundational in computing. To count from 0 to 5 (base 10) in binary:\n",
    "\n",
    "```python\n",
    "0 = 0b0000\n",
    "1 = 0b0001\n",
    "2 = 0b0010\n",
    "3 = 0b0011\n",
    "4 = 0b0100\n",
    "5 = 0b0101\n",
    "```\n",
    "\n",
    "To see visually that `100 (base 10)` is equal to `1100100 (base 2)` (or **0b**`1100100`, where **b** stands for binary):\n",
    "\n",
    "```text\n",
    "0b1100100\n",
    "  ││││││└ 0 × 2^0 = 0 × 1  = 0\n",
    "  │││││└─ 0 × 2^1 = 0 × 2  = 0\n",
    "  ││││└── 1 x 2^2 = 1 × 4  = 4\n",
    "  │││└─── 0 × 2^3 = 0 × 8  = 0\n",
    "  ││└──── 0 × 2^4 = 0 × 16 = 0\n",
    "  │└───── 1 × 2^5 = 1 × 32 = 32\n",
    "  └────── 1 × 2^6 = 1 × 64 = 64\n",
    "                             __\n",
    "                             100\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3283f8ad",
   "metadata": {},
   "source": [
    "Python has built-in functions `bin()`, `oct()`, `hex()`, and `int()` for converting between number systems. Python represents binary, octal, and hexadecimal literals with the prefixes **0b**, **0o**, and **0x**. When using `int()` for conversion, you provide the base of the input string. Python also recognizes these literal prefixes and automatically evaluates the values in base 10."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "651a939d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b1100100\n",
      "0o144\n",
      "0x64\n",
      "0x64\n",
      "100\n",
      "100\n"
     ]
    }
   ],
   "source": [
    "num_b = bin(100)            # '0b1100100'\n",
    "num_o = oct(100)            # '0o144'\n",
    "num_h = hex(100)            # '0x64', converted from 100\n",
    "num_h2 = hex(0b1100100)     # '0x64', converted from base 2\n",
    "num_i_h = int(num_h, 16)    # '100'\n",
    "num_i_b = int(num_b, 2)     # '100'\n",
    "\n",
    "print(num_b, num_o, num_h, num_h2, num_i_h, num_i_b, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e7a037e",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Number System Conversions\n",
    "# Q1. What's the value of 10 (base 10) in binary? (Print it as a string if you use it as a literal)\n",
    "# Q2. What's the value of decimal 64 in base 16?\n",
    "# Try to produce the same output as the cell below. # You may need to use the print() function.\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code stops here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "233f4beb",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0b1010\n",
      "0x40\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "print(bin(10))  ### or print(\"0b1010\") \n",
    "print(hex(64))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96afab8f",
   "metadata": {},
   "source": [
    "### Character Encoding\n",
    "\n",
    "For computers, the smallest unit of data is a **bit** (binary digit). A bit can only be 0 or 1, which can represent states such as off/on, false/true, or no voltage/voltage. A **byte** is a group of 8 bits. Because 8 bits can represent 2^8, or 256, different values (0-255), the byte is the fundamental addressable unit in modern computing.\n",
    "\n",
    "Computers process machine code, so text needs to be represented numerically. That representation is called **encoding**. For example, the letter **A** is represented as 65 (base 10), or 0b1000001, in the ASCII (American Standard Code for Information Interchange) code table. ASCII encoding covers English letters, numbers, and common special characters. An early version of the ASCII table is MIL-STD-188-100:\n",
    "\n",
    "```{figure} ../../figures/ascii-code-chart.png\n",
    ":name: ascii-code-chart\n",
    ":alt: ASCII Code Chart 1972\n",
    ":width: 60%\n",
    ":align: center\n",
    "\n",
    "[ASCII](https://en.wikipedia.org/wiki/ASCII) code chart, 1972. Public domain, via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:USASCII_code_chart.png).\n",
    "```\n",
    "\n",
    "In this chart, you can see that the letter **A** has the binary value `1000001`. When comparing string or character literals, we can say that `'B'` is greater than `'A'` because of the encoding: the ASCII value of `'B'` is 66, which is greater than the ASCII value of `'A'`, 65.\n",
    "\n",
    "Since ASCII only represents a limited set of English characters, the [Unicode Standard](https://en.wikipedia.org/wiki/Unicode) and Unicode Transformation Format (UTF) schemes were developed to support text from the world's writing systems. Among these schemes, [**UTF-8**](https://en.wikipedia.org/wiki/UTF-8) is the dominant encoding system on the internet and is supported by all modern operating systems and programming languages.\n",
    "\n",
    "ASCII uses 1 byte (7 bits originally and 8 bits for extended ASCII) to represent each character for its standard 128 characters, while UTF-8 is variable-length, using 1 to 4 byte code units (8 to 32 bits) to support 1,112,064 code points, while also encoding standard ASCII characters in just 1 byte for backwards-compatibility. With the large number of code points supported, UTF-8 is able to represent emojis and East Asian language characters."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1f5c429",
   "metadata": {},
   "source": [
    "```{index} character encoding, bit, byte, ASCII, Unicode, UTF-8\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-ord-chr",
   "metadata": {},
   "source": [
    "#### Character Codes in Python\n",
    "\n",
    "You do not need to look up character codes in a table; Python can do it for you. The built-in function **`ord()`** takes a single character and returns its **code point**, the integer that represents it in Unicode. For the characters in the ASCII table, the code point is the same as the ASCII code. The built-in function **`chr()`** does the reverse: it takes an integer code and returns the character.\n",
    "\n",
    "| Function | Input | Output | Example |\n",
    "|---|---|---|---|\n",
    "| `ord(char)` | a one-character string | an integer code | `ord('A')` returns `65` |\n",
    "| `chr(code)` | an integer code | a one-character string | `chr(65)` returns `'A'` |\n",
    "\n",
    "Combined with `bin()` and `hex()` from the previous section, `ord()` lets you see the same character as a decimal, binary, or hexadecimal number."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch01-ord-chr-index",
   "metadata": {},
   "source": [
    "```{index} ord(), chr(), code point\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch01-ord-chr-example",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "65\n",
      "0b1000001\n",
      "0x41\n",
      "A\n",
      "1\n",
      "True\n",
      "233\n",
      "π\n"
     ]
    }
   ],
   "source": [
    "### character to code and back\n",
    "code = ord('A')\n",
    "print(code)              # 65\n",
    "print(bin(code))         # 0b1000001\n",
    "print(hex(code))         # 0x41\n",
    "print(chr(code))         # A\n",
    "\n",
    "### why 'B' > 'A' is True: Python compares the codes\n",
    "print(ord('B') - ord('A'))   # 1\n",
    "print('B' > 'A')             # True\n",
    "\n",
    "### beyond ASCII: Unicode code points\n",
    "print(ord('é'))          # 233\n",
    "print(chr(960))          # π"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "bab31adb",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Character Codes\n",
    "### What's the decimal code for the letter \"C\" in the ASCII code? Save it to a variable named c_dec using the ord() function.\n",
    "### What's the binary code for the letter \"C\" in the ASCII code? Save it to a variable named c_bin using the bin() function.\n",
    "### Use print() with a comma between the label and the value to produce these two lines:\n",
    "### Decimal code for C: 67\n",
    "### Binary code for C: 0b1000011\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code stops here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "476b06c3",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Decimal code for C: 67\n",
      "Binary code for C: 0b1000011\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "c_dec = ord(\"C\")\n",
    "c_bin = bin(c_dec)\n",
    "print(\"Decimal code for C:\", c_dec)\n",
    "print(\"Binary code for C:\", c_bin)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a46add75-59ab-4dad-bc14-f9d903c063ec",
   "metadata": {},
   "source": [
    "## Resources\n",
    "\n",
    "**Official Python Documentation**\n",
    "\n",
    "1. [PEP 20 - The Zen of Python](https://pep.python.org/pep-0020/)\n",
    "2. [The Python Standard Library](https://docs.python.org/3/library/index.html)\n",
    "3. [The Python Language Reference](https://docs.python.org/3/reference/index.html)\n",
    "4. [Python Tutorial (Official)](https://docs.python.org/3/tutorial/index.html)\n",
    "5. [Python Package Index (PyPI)](https://pypi.org/) - Repository of third-party Python packages\n",
    "\n",
    "**Style Guides and Best Practices**\n",
    "\n",
    "1. [PEP 8 - Style Guide for Python Code](https://pep.python.org/pep-0008/)\n",
    "2. [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html) - Industry-standard style guide used at Google; differs from PEP8 in places such as forbidding wildcard imports (from X import *) and more structured docstrings for functions/methods. \n",
    "\n",
    "**Tutorials**\n",
    "\n",
    "- [Real Python](https://realpython.com/) - Tutorials and articles on Python programming\n",
    "- [Python for Everybody](https://www.py4e.com/) - Free interactive textbook and course\n",
    "- [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/) - Practical programming for beginners\n",
    "\n",
    "**Interactive Practice**\n",
    "\n",
    "- [Python Tutor](https://pythontutor.com/) - Visualize code execution step by step\n",
    "- [LeetCode](https://leetcode.com/) - Coding practice and interview preparation\n",
    "- [HackerRank Python](https://www.hackerrank.com/domains/python) - Practice problems and challenges"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7dd86c7c-ecbf-4b53-b33a-0d38c8bf7761",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
