{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e2a34053",
   "metadata": {},
   "source": [
    "# 🐍 Python and notebooks: the basics\n",
    "\n",
    "This short notebook is **optional**. It is meant for you if you have never, or hardly ever, worked with Python or in a Jupyter notebook: you learn how a notebook works, which building blocks of Python the notebooks of AI voor Iedereen use, and how Colab's built-in AI can explain code to you. Along the way, you build a very small AI yourself: a rule that tells apples from pears by their size.\n",
    "\n",
    "Already at home in Python and notebooks? Then skip this one: the other notebooks don't build on it.\n",
    "\n",
    "**Prior knowledge**: none.\n",
    "\n",
    "**Estimated time**: about 25 minutes.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/python-basics](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/14AGgFoYDVR4NmcBYcEeDqL921invXXcS?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d55f29c1",
   "metadata": {},
   "source": [
    "## 📓 How a notebook works\n",
    "\n",
    "A **Jupyter notebook** is a document that mixes text, like this paragraph, with **code cells** that you can run. [Google Colab](https://colab.research.google.com) runs that code on a Google computer, so you don't have to install anything; you only need a (free) Google account.\n",
    "\n",
    "**New to Colab?** [This 8-minute video](https://www.youtube.com/watch?v=5sgJsCah9bs) shows the basics: running a cell, adding your own code cells and text cells (like this one, written in [Markdown](https://colab.research.google.com/notebooks/markdown_guide.ipynb)), moving and deleting cells, and naming your notebook.\n",
    "\n",
    "1. **First make your own copy**: in the menu at the top left, just below the notebook's name, choose *File → Save a copy in Drive*. The copy opens in a new tab. Work in that copy: there you can change and save everything.\n",
    "2. **Run a cell** (i.e. execute its code) by clicking in it and pressing **Shift+Enter** (runs the cell and jumps to the next one) or **Ctrl+Enter** (runs the cell and stays there; on a Mac: **⌘+Enter**). You can also click the ▶ button to the left of a cell. The result appears right below the cell.\n",
    "3. **Run the cells in order, from top to bottom.** A cell can use what the cells above it created. If you skip one, you get an error such as `NameError: name 'fruit' is not defined`. Then simply run the cells above it first (*Runtime → Run before*).\n",
    "4. **You can't break anything.** If something behaves strangely, choose *Runtime → Restart session* and run the cells again from the top.\n",
    "\n",
    "The first cell you run takes a few seconds, because Colab first starts a computer for you. If Colab warns that this notebook was not authored by Google, choose *Run anyway*. After a while without activity, Colab stops that computer and forgets what the cells made: then run them from the top again.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/python-basics.ipynb) and run it on your own computer. You need Python and a program that opens notebooks: follow the [Jupyter installation guide](https://jupyter.org/install), or open the file in [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks). All the code in this notebook works there too."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "320900b3",
   "metadata": {},
   "source": [
    "## ▶️ Your first cell\n",
    "\n",
    "Click in the cell below and press **Shift+Enter** (or the ▶ button to its left) to run the code."
   ]
  },
  {
   "cell_type": "code",
   "id": "4b902055",
   "metadata": {},
   "source": [
    "import random\n",
    "\n",
    "number = random.randint(1, 100)  # a random whole number from 1 to 100\n",
    "print(\"Your random number is\", number)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "e2f439e5",
   "metadata": {},
   "source": [
    "Below the cell you now see a random number. Run the cell a few more times (**Ctrl+Enter** keeps you in the same cell): every time, you get a new number. By the end of this notebook, you can read every line of it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0179996c",
   "metadata": {},
   "source": [
    "## 🔢 Values and variables\n",
    "\n",
    "The tables in this notebook list the building blocks of Python that you will meet most often. Skim them, run the example below each table, and come back to them whenever a line in another notebook puzzles you.\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `x = 5` | Stores the value 5 under the name `x` (a **variable**). `x = x + 1`, or shorter `x += 1`, makes it one more. |\n",
    "| `2 * x`, `x / 2` | Arithmetic: multiply and divide, just like `+` and `-`. |\n",
    "| `# a note` | A **comment**: an explanation for people, which Python skips. |\n",
    "| `\"apple\"` | A piece of text, a **string**, between quotes. |\n",
    "| `print(\"x is\", x)` | Shows text and values below the cell. |\n",
    "| `f\"x is {x}\"` | An **f-string**: Python fills in the value of `x` between the braces. `f\"{ratio:.2f}\"` shows `ratio` with two decimals. |\n",
    "| `x == 5`, `x != 5`, `x < 5` | **Comparisons**: equal, not equal, less than. The result is `True` or `False`. One `=` stores a value, two `==` compare. `x > 1 and x < 5` combines two conditions; so does `or`, and `not` turns a condition around. |"
   ]
  },
  {
   "cell_type": "code",
   "id": "f871cbbb",
   "metadata": {},
   "source": [
    "# An apple: its width and height in millimeters\n",
    "width = 57\n",
    "height = 63\n",
    "\n",
    "ratio = height / width  # the height divided by the width\n",
    "print(\"Height divided by width:\", ratio)\n",
    "print(f\"Rounded: {ratio:.2f}\")\n",
    "ratio > 1.2  # is this piece of fruit more than 1.2 times as tall as it is wide?"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "2c8a418e",
   "metadata": {},
   "source": [
    "The cell shows two lines of text, and then `False`: a cell also shows the value of its last line, without `print`. This apple is only 1.11 times as tall as it is wide.\n",
    "\n",
    "**Try it**: change the height into `103`, the height of a pear, and run the cell again."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27286e66",
   "metadata": {},
   "source": [
    "## 📋 Lists, tuples and dictionaries\n",
    "\n",
    "AI works with data: many examples at once. Python keeps them together in lists, tuples and dictionaries.\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `[3, 6, 12]` | A **list**. If `numbers = [3, 6, 12]`, then `numbers[0]` is the first item (counting starts at 0), `numbers[-1]` the last and `len(numbers)` how many there are. `numbers.append(24)` adds an item at the end, `numbers + [24]` gives a new, longer list, and `numbers.clear()` empties it. |\n",
    "| `(57, 63, \"apple\")` | A **tuple**: a few values that belong together, such as the width, the height and the kind of one piece of fruit. `width, height, kind = (57, 63, \"apple\")` splits it into three variables. |\n",
    "| `{\"apple\": \"red\", \"pear\": \"limegreen\"}` | A **dictionary**: values stored under a key, like words in a real dictionary. `colors[\"pear\"]` looks up the value under `\"pear\"`, and `colors[\"plum\"] = \"purple\"` stores a new one. |"
   ]
  },
  {
   "cell_type": "code",
   "id": "a91f6db6",
   "metadata": {},
   "source": [
    "# A few apples and pears: (width, height, kind) for every piece of fruit\n",
    "fruit = [(57, 63, \"apple\"), (74, 61, \"apple\"), (66, 69, \"apple\"), (78, 80, \"apple\"),\n",
    "         (62, 83, \"pear\"), (61, 103, \"pear\"), (74, 96, \"pear\"), (58, 81, \"pear\")]\n",
    "print(len(fruit), \"pieces of fruit\")\n",
    "print(\"The first one:\", fruit[0])\n",
    "\n",
    "width, height, kind = fruit[-1]  # split the last one into three variables\n",
    "print(\"The last one is a\", kind, \"of\", width, \"by\", height, \"mm\")\n",
    "\n",
    "colors = {\"apple\": \"red\", \"pear\": \"limegreen\"}  # a color for every kind of fruit\n",
    "colors[\"pear\"]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "f7967353",
   "metadata": {},
   "source": [
    "This is how AI code usually stores its data: a list of **examples**, each with a few numbers that describe it (its **features**: here the width and the height) and the right answer (its **label**: apple or pear). The machine learning notebooks keep the two apart: the features in a table `X`, with one row per example, and the labels in a list `y`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ce25fad",
   "metadata": {},
   "source": [
    "## 🔁 Loops and choices\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `for n in numbers:` | A **loop**: runs the indented lines below it once for every item, with `n` the current item. `for width, height, kind in fruit:` splits every tuple on the fly, `for i in range(5):` runs the lines for `i` = 0, 1, 2, 3 and 4, and `for key, value in colors.items():` goes through a dictionary. |\n",
    "| `if x > 1:` | Runs the indented lines below it only if the condition is true; the lines under `else:` run otherwise. With `elif` (else if), you test another condition first. `\"pear\" if x > 1 else \"apple\"` makes such a choice within one line. |\n",
    "\n",
    "**Indentation matters**: the spaces at the start of a line tell Python which lines belong to a `for`, `if`, `else` or `def`."
   ]
  },
  {
   "cell_type": "code",
   "id": "62a22bd1",
   "metadata": {},
   "source": [
    "for width, height, kind in fruit:  # one round for every piece of fruit\n",
    "    if height > 1.2 * width:\n",
    "        guess = \"pear\"\n",
    "    else:\n",
    "        guess = \"apple\"\n",
    "    print(f\"{width} by {height} mm: the rule says {guess}, the label says {kind}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "7cbc9c03",
   "metadata": {},
   "source": [
    "The `print` belongs to the loop but not to the `else`, so it runs once for every piece of fruit. With 1.2 as the threshold, the rule is right every time.\n",
    "\n",
    "**Try it**: change `1.2` into `1.0` and run the cell again. Which apples does the rule now take for pears?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97f86a27",
   "metadata": {},
   "source": [
    "## ⚙️ Functions\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `def double(x):` | Defines a **function** called `double` with an input `x`. The indented lines below it do the work, and `return 2 * x` gives back the result. Text between `\"\"\"` right below the first line describes what the function does. Defining a function doesn't run it yet: `double(4)` does, and gives 8. |\n",
    "| `def classify(width, height, threshold=1.2):` | A **default value**: when you call the function, you may leave out `threshold`, and it is then 1.2. |\n",
    "| `random.randint(1, 100)` | Calls the function `randint` from the package `random`. The dot also calls something that belongs to a value: `numbers.append(24)`. |\n",
    "| `plt.scatter(width, height, color=\"red\")` | An input given by its name (a **keyword argument**), so that you can skip the inputs you don't need. |\n",
    "| `len(numbers)`, `min(3, 5)`, `round(2.56, 1)` | Functions that are always available: `len`, `min`, `max`, `sum`, `round` and `sorted`. |"
   ]
  },
  {
   "cell_type": "code",
   "id": "e23a930a",
   "metadata": {},
   "source": [
    "def classify(width, height, threshold=1.2):\n",
    "    \"\"\"Guess the kind of fruit: a pear if it is more than threshold times as tall as it is wide.\"\"\"\n",
    "    if height > threshold * width:\n",
    "        return \"pear\"\n",
    "    else:\n",
    "        return \"apple\"\n",
    "\n",
    "\n",
    "print(classify(61, 103))\n",
    "print(classify(70, 80))\n",
    "print(classify(70, 80, threshold=1.1))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "6b033eb5",
   "metadata": {},
   "source": [
    "The function holds the rule from the loop above, with the threshold as an input. A piece of fruit of 70 by 80 mm is 1.14 times as tall as it is wide: an apple for the threshold 1.2, but a pear for 1.1."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3037ac9f",
   "metadata": {},
   "source": [
    "## 📦 Packages and notebook commands\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `import random` | Loads a **package**: a collection of ready-made functions, here for random numbers, so that you don't have to write everything from scratch. |\n",
    "| `import matplotlib.pyplot as plt` | Loads (a part of) a package under a short nickname, so that you can write `plt.scatter(...)`. |\n",
    "| `from sklearn.svm import SVC` | Loads one thing from a package, so that you can write `SVC()` without the name of the package in front. |\n",
    "| `%pip install matplotlib` | Not Python but an instruction to the notebook program: `pip`, Python's package installer, downloads the package `matplotlib` so that you can import it. Colab already has the most common packages, so there the line changes nothing. |\n",
    "| `threshold = 1.0  # @param {...}` | A comment that Colab turns into an input next to the code: a slider, a text field (`# @param {type:\"string\"}`) or a dropdown menu (`# @param [\"apple\", \"pear\"]`). Choosing there changes the code. In other notebook programs, it is just a comment. |\n",
    "\n",
    "The notebooks use a few well-known packages for AI: [NumPy](https://numpy.org) for computing with many numbers at once, [pandas](https://pandas.pydata.org) for tables, [matplotlib](https://matplotlib.org) for charts and [scikit-learn](https://scikit-learn.org) for machine learning."
   ]
  },
  {
   "cell_type": "code",
   "id": "72626b2a",
   "metadata": {},
   "source": [
    "# On your own computer, this installs matplotlib (Colab has it already)\n",
    "%pip install --quiet matplotlib"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "3c056dec",
   "metadata": {},
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "threshold = 1.0  # @param {type:\"slider\", min:1.0, max:1.5, step:0.05}\n",
    "\n",
    "correct = 0  # how many guesses are right\n",
    "for width, height, kind in fruit:\n",
    "    plt.scatter(width, height, color=colors[kind])  # a dot for every piece of fruit\n",
    "    if classify(width, height, threshold) == kind:\n",
    "        correct += 1\n",
    "plt.plot([50, 90], [threshold * 50, threshold * 90], color=\"gray\")  # the rule: height = threshold × width\n",
    "plt.title(f\"Threshold {threshold}: {correct} of {len(fruit)} right\")\n",
    "plt.xlabel(\"width (mm)\")\n",
    "plt.ylabel(\"height (mm)\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "2c2834d0",
   "metadata": {},
   "source": [
    "Every dot is a piece of fruit: red for an apple, green for a pear. Above the gray line, the rule says pear. With the threshold 1.0, the line lies too low, and the rule takes three round apples for pears.\n",
    "\n",
    "**Try it**: move the slider next to the code (in other notebook programs: change the number) and run the cell again. Which thresholds get all eight right?\n",
    "\n",
    "Trying thresholds until the rule makes as few mistakes as possible on the examples: in a nutshell, that is what **training** means in machine learning. There, the computer does the trying, with many more examples and features."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49651714",
   "metadata": {},
   "source": [
    "## ✨ Getting help from AI\n",
    "\n",
    "Colab has an AI assistant built in: Gemini, Google's large language model. It can explain code that puzzles you, here and in the other notebooks, and change code for you.\n",
    "\n",
    "Click in a code cell: a small toolbar appears at its top right. The button with a pen and a little star, called *Available AI features*, opens a menu:\n",
    "\n",
    "| Choice | What it does |\n",
    "| --- | --- |\n",
    "| *Explain code* | Gemini explains the code in a chat panel on the right. Select a few lines first to have only those explained. Ask follow-up questions in the same chat. |\n",
    "| *Transform code* | Type how the code should change (\"add a comment to every line\"), and Gemini proposes new code, with the changes marked. *Accept* keeps it, *Accept and run* also runs it, *Reject* keeps the old code. |\n",
    "| *Generate code* | In an empty cell: describe what the code should do, and Gemini writes it. |\n",
    "\n",
    "*Transform code* only works in your own copy (*File → Save a copy in Drive*). No AI choices at all? Colab only offers them to Google accounts of people aged 18 or older. In other notebook programs, paste the code into a chatbot instead."
   ]
  },
  {
   "cell_type": "code",
   "id": "9d598ae1",
   "metadata": {},
   "source": [
    "# How tall are the pears, compared to their width?\n",
    "pears = [(width, height) for width, height, kind in fruit if kind == \"pear\"]\n",
    "ratios = [height / width for width, height in pears]\n",
    "average = sum(ratios) / len(ratios)\n",
    "print(f\"{len(pears)} pears, on average {average:.2f} times as tall as they are wide\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "7b0c6ed2",
   "metadata": {},
   "source": [
    "The first two lines each build a list in one line, which none of the tables above explains: a job for the AI button.\n",
    "\n",
    "**Try it**:\n",
    "\n",
    "1. Run the cell above. Then click the AI button and choose *Explain code*. Does the explanation match what the cell prints?\n",
    "2. Choose *Transform code* and ask: \"Do the same for the apples.\" Look at what Gemini changes, then choose *Accept and run*. Do the two averages fit the thresholds that got all eight right in the plot above?\n",
    "\n",
    "Gemini is a language model: with short code like this, it is usually right, but it can [sound sure and still be wrong](https://ai.kuleuven.be/aivooriedereen/en/large-language-models#hallucinations). So run the code it writes and check the result. And ask it to explain, not only to fix: that is how you learn to read code yourself."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11673b7a",
   "metadata": {},
   "source": [
    "## 🧯 When something goes wrong\n",
    "\n",
    "Sooner or later, a cell stops with an **error**. That happens to experienced programmers all the time. Read the **last line** first: it names the kind of error and what went wrong. Below the error, Colab also offers an *Explain error* button: Gemini then explains the error and proposes a fix.\n",
    "\n",
    "| Error | What it usually means |\n",
    "| --- | --- |\n",
    "| `NameError: name 'fruit' is not defined` | Python doesn't know that name: you skipped a cell above, or there is a typo in the name. |\n",
    "| `SyntaxError` or `IndentationError` | The line isn't valid Python: often a missing parenthesis, quote or colon, or spaces at the start of the line that don't line up with the lines around it. |\n",
    "| `ModuleNotFoundError: No module named 'matplotlib'` | The package isn't installed: run the cell with `%pip install` above it. |\n",
    "| `KeyError: 'plum'` | That key isn't in the dictionary. |\n",
    "\n",
    "**Try it**: in the cell with `def classify`, change `width` in the line with `if` into `widht`, run the cell and read the last line of the error. Then click *Explain error*: does Gemini say the same? Accept its fix, or undo the change yourself (**Ctrl+Z**, on a Mac **⌘+Z**), and run the cell again."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac0ee58b",
   "metadata": {},
   "source": [
    "## 🏁 What next?\n",
    "\n",
    "That's all you need to get started. Every other notebook has a short table near the start, with the Python it uses on top of these basics. And when a line there still puzzles you, the AI button can explain it.\n",
    "\n",
    "Want to learn more Python? The official [Python tutorial](https://docs.python.org/3/tutorial/) explains everything in these tables, and much more."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1c98e34",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/python-basics](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [],
   "language": "en",
   "title": "Python and notebooks: the basics"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
