{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 6: Error handling and file basics\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 3, Thursday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. When a cell reads input, a small box appears: type the values there and press Enter. The practice problems are in a separate notebook, topic-06-practice.ipynb.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. Errors and how to read them\n",
    "2. try and except\n",
    "3. Catching the right error\n",
    "4. else and finally\n",
    "5. try in loops and functions\n",
    "6. Raising your own errors\n",
    "7. File basics\n",
    "8. Common mistakes\n",
    "9. Solved problems (easy to medium-hard)\n",
    "10. Practice problems (try them yourself) (in topic-06-practice.ipynb)\n",
    "11. Check yourself (on the website)\n",
    "12. Quick summary"
   ],
   "id": "t06-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: error handling and file basics\n",
    "\n",
    "What matters most in this lesson. Four things matter most today: reading the last line of an error message (the type, then the explanation); the basic `try` and `except` with a named error type; putting `try` inside a loop so that one bad value does not stop the others; and opening a file with `with` to write and read text.\n",
    "\n",
    "`else`, `finally` and `raise` are a first look. You will use them more in later topics. There are 15 solved problems. Start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to handling errors with `try` and `except`, so that a program does not crash when something goes wrong. It starts from the simplest examples and gets harder step by step: what an error is, the common error types, `try` and `except`, several error types, `else` and `finally`, `try` in loops and functions, and raising your own errors. A short part at the end shows the basics of reading and writing files. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.\n",
    "\n",
    "You should already know variables, data types, `if/else`, loops, functions, lists, dictionaries and comprehensions.\n",
    "\n",
    "## 1. Errors and how to read them\n",
    "\n",
    "### 1.1 A program that stops\n",
    "\n",
    "```python\n",
    "print(\"Start\")\n",
    "number = int(\"abc\")\n",
    "print(\"End\")\n",
    "```\n",
    "\n",
    "```\n",
    "Start\n",
    "ValueError: invalid literal for int() with base 10: 'abc'\n",
    "```\n",
    "\n",
    "`Start` was printed, then the program stopped. `End` was never printed. An error that happens while the program runs is called an exception.\n",
    "\n",
    "### 1.2 How to read the message\n",
    "\n",
    "The last line of the message has two parts:\n",
    "\n",
    "```\n",
    "ValueError: invalid literal for int() with base 10: 'abc'\n",
    "```\n",
    "\n",
    "- Before the colon: the type of the error (`ValueError`).\n",
    "- After the colon: the explanation.\n",
    "\n",
    "Always read this line first. The type tells you what kind of problem it is, and the type is also what `try/except` works with.\n",
    "\n",
    "### 1.3 Syntax errors are different\n",
    "\n",
    "A `SyntaxError` means the code itself is not written correctly. Python finds it before running anything, so not even the first line runs:\n",
    "\n",
    "```python\n",
    "print(\"Start\")\n",
    "if 5 > 3\n",
    "    print(\"yes\")\n",
    "```\n",
    "\n",
    "```\n",
    "SyntaxError: expected ':'\n",
    "```\n",
    "\n",
    "`Start` was not printed. A syntax error cannot be handled while the program runs. You fix it in the code.\n",
    "\n",
    "|  | Syntax error | Exception |\n",
    "| --- | --- | --- |\n",
    "| When | before the program starts | while the program runs |\n",
    "| Cause | the code is written wrongly | a value or a situation the code cannot handle |\n",
    "| What to do | fix the code | fix the code, or handle it with `try/except` |\n",
    "\n",
    "### 1.4 The common error types\n",
    "\n",
    "You have already met most of them in earlier lessons:\n",
    "\n",
    "| Error type | When it happens | Example |\n",
    "| --- | --- | --- |\n",
    "| `ValueError` | the type is right but the value is not | `int(\"abc\")` |\n",
    "| `TypeError` | the type is wrong for this operation | `\"5\" + 5` |\n",
    "| `ZeroDivisionError` | division by zero | `10 / 0` |\n",
    "| `IndexError` | a list index that does not exist | `[1, 2, 3][5]` |\n",
    "| `KeyError` | a dictionary key that does not exist | `{\"a\": 1}[\"b\"]` |\n",
    "| `NameError` | a name that was never created | `print(totl)` |\n",
    "| `AttributeError` | a method that this type does not have | `\"abc\".append(\"d\")` |\n",
    "\n",
    "```python\n",
    "print(10 / 0)\n",
    "```\n",
    "\n",
    "```\n",
    "ZeroDivisionError: division by zero\n",
    "```\n",
    "\n",
    "```python\n",
    "print(\"5\" + 5)\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: can only concatenate str (not \"int\") to str\n",
    "```\n",
    "\n",
    "```python\n",
    "numbers = [1, 2, 3]\n",
    "print(numbers[5])\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: list index out of range\n",
    "```\n",
    "\n",
    "```python\n",
    "prices = {\"apple\": 1.5}\n",
    "print(prices[\"kiwi\"])\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 'kiwi'\n",
    "```\n",
    "\n",
    "```python\n",
    "total = 100\n",
    "print(totl)\n",
    "```\n",
    "\n",
    "```\n",
    "NameError: name 'totl' is not defined. Did you mean: 'total'?\n",
    "```\n",
    "\n",
    "Python even suggests the name you probably meant.\n",
    "\n",
    "Two kinds of causes. Some errors are mistakes in the code (a misspelled name, a wrong index): you fix the code. Others come from outside (the user types letters instead of a number): the code is fine, but it must be ready for them. `try/except` is for the second kind.\n",
    "\n",
    "## 2. `try` and `except`\n",
    "\n",
    "### 2.1 The basic form\n",
    "\n",
    "Change it and run: change `\"abc\"` to `\"7\"`. Which lines run now?"
   ],
   "id": "t06-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    number = int(\"abc\")\n",
    "    print(\"This line is skipped\")\n",
    "except ValueError:\n",
    "    print(\"That is not a number\")\n",
    "\n",
    "print(\"The program continues\")"
   ],
   "id": "t06-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "try:\n",
    "    # code that may cause an error\n",
    "except ErrorType:\n",
    "    # what to do if that error happens\n",
    "```\n",
    "\n",
    "The program did not stop. Python tried the code, the error happened, and the `except` block ran instead.\n",
    "\n",
    "### 2.2 How Python runs it\n",
    "\n",
    "1. Python runs the lines of the `try` block.\n",
    "2. If an error happens, the rest of the `try` block is skipped and Python jumps to `except`.\n",
    "3. If no error happens, the `except` block is skipped.\n",
    "4. In both cases the program continues below.\n",
    "\n",
    "The same code with a value that works:"
   ],
   "id": "t06-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    number = int(\"42\")\n",
    "    print(\"Converted:\", number)\n",
    "except ValueError:\n",
    "    print(\"That is not a number\")\n",
    "\n",
    "print(\"The program continues\")"
   ],
   "id": "t06-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "|  | Error in `try` | No error in `try` |\n",
    "| --- | --- | --- |\n",
    "| Lines of `try` after the error | skipped | all run |\n",
    "| `except` block | runs | skipped |\n",
    "| Code below | runs | runs |\n",
    "\n",
    "### 2.3 With input from the user\n",
    "\n",
    "Change it and run: type `20` in the input box, then type `twenty` again.\n",
    "\n",
    "When the cell asks for input, type `twenty`."
   ],
   "id": "t06-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "twenty"
     ]
    }
   },
   "outputs": [],
   "source": [
    "text = input(\"How old are you? \")\n",
    "try:\n",
    "    age = int(text)\n",
    "    print(\"Next year you will be\", age + 1)\n",
    "except ValueError:\n",
    "    print(\"Please type a whole number\")"
   ],
   "id": "t06-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4 A value to continue with\n",
    "\n",
    "Often the `except` block gives the variable a default value, so the rest of the program can go on:\n",
    "\n",
    "Change it and run: change `\"abc\"` to `\"5\"`."
   ],
   "id": "t06-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = \"abc\"\n",
    "try:\n",
    "    quantity = int(text)\n",
    "except ValueError:\n",
    "    quantity = 1\n",
    "\n",
    "print(\"Quantity:\", quantity)"
   ],
   "id": "t06-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Catching the right error\n",
    "\n",
    "### 3.1 An `except` catches only the type you name\n",
    "\n",
    "Another type still stops the program:\n",
    "\n",
    "```python\n",
    "try:\n",
    "    result = 10 / 0\n",
    "except ValueError:\n",
    "    print(\"That is not a number\")\n",
    "```\n",
    "\n",
    "```\n",
    "ZeroDivisionError: division by zero\n",
    "```\n",
    "\n",
    "### 3.2 Several `except` blocks\n",
    "\n",
    "Change it and run: add a call `divide(\"0\", \"10\")`. Is that an error?"
   ],
   "id": "t06-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def divide(a, b):\n",
    "    try:\n",
    "        print(int(a) / int(b))\n",
    "    except ValueError:\n",
    "        print(\"Please use whole numbers\")\n",
    "    except ZeroDivisionError:\n",
    "        print(\"Cannot divide by zero\")\n",
    "\n",
    "divide(\"10\", \"2\")\n",
    "divide(\"ten\", \"2\")\n",
    "divide(\"10\", \"0\")"
   ],
   "id": "t06-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python uses the first `except` block whose type matches, and only that one.\n",
    "\n",
    "### 3.3 One block for several types\n",
    "\n",
    "When the reaction is the same, write the types as a tuple:"
   ],
   "id": "t06-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    print(int(\"10\") / int(\"0\"))\n",
    "except (ValueError, ZeroDivisionError):\n",
    "    print(\"Bad input\")"
   ],
   "id": "t06-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.4 The error message: `as error`\n",
    "\n",
    "`as error` stores the error in a variable, so you can print its explanation:\n",
    "\n",
    "Change it and run: change `\"abc\"` to `\"3.5\"` and read the new message."
   ],
   "id": "t06-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    number = int(\"abc\")\n",
    "except ValueError as error:\n",
    "    print(\"Problem:\", error)"
   ],
   "id": "t06-014"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [1, 2, 3]\n",
    "try:\n",
    "    print(numbers[5])\n",
    "except IndexError as error:\n",
    "    print(\"Problem:\", error)\n",
    "    print(\"Type:\", type(error).__name__)"
   ],
   "id": "t06-015"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.5 `Exception`: almost every error\n",
    "\n",
    "`Exception` matches almost every error type. Use it as the last block, for the cases you did not expect, and print the message so that the problem is not hidden:\n",
    "\n",
    "Change it and run: add a call `show(\"50\", 0)`."
   ],
   "id": "t06-016"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def show(value, index):\n",
    "    try:\n",
    "        print(10 / value[index])\n",
    "    except ZeroDivisionError:\n",
    "        print(\"Cannot divide by zero\")\n",
    "    except Exception as error:\n",
    "        print(\"Unexpected problem:\", type(error).__name__, \"-\", error)\n",
    "\n",
    "show([5, 0], 0)\n",
    "show([5, 0], 1)\n",
    "show([5, 0], 7)\n",
    "show(5, 0)"
   ],
   "id": "t06-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The order matters: specific types first, `Exception` last. If `Exception` came first, it would catch everything and the other blocks would never run.\n",
    "\n",
    "### 3.6 Do not hide errors\n",
    "\n",
    "An `except:` without a type catches every error, also the ones that are real mistakes in your code:\n",
    "\n",
    "Change it and run: change `except:` to `except ValueError:`. Now Python shows the real problem."
   ],
   "id": "t06-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    total = 10 + numbr\n",
    "except:\n",
    "    print(\"Something went wrong\")"
   ],
   "id": "t06-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The real problem is a misspelled name (`numbr`), but the message hides it. Name the error type you expect. Then unexpected errors still stop the program and show you where the mistake is.\n",
    "\n",
    "| Form | Catches | Use it |\n",
    "| --- | --- | --- |\n",
    "| `except ValueError:` | one type | most of the time |\n",
    "| `except (ValueError, KeyError):` | the listed types | the same reaction for several types |\n",
    "| `except ValueError as error:` | one type, and gives the message | when you want to show or save the explanation |\n",
    "| `except Exception as error:` | almost everything | as the last block, and always print the message |\n",
    "| `except:` | everything | avoid it |\n",
    "\n",
    "## 4. `else` and `finally`\n",
    "\n",
    "- `else` runs only if no error happened in `try`.\n",
    "- `finally` runs always, with or without an error.\n",
    "\n",
    "Change it and run: add a call `read_number(\"3.5\")`."
   ],
   "id": "t06-020"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_number(text):\n",
    "    try:\n",
    "        number = int(text)\n",
    "    except ValueError:\n",
    "        print(\"Not a number:\", text)\n",
    "    else:\n",
    "        print(\"Success:\", number)\n",
    "    finally:\n",
    "        print(\"Done with\", text)\n",
    "\n",
    "read_number(\"42\")\n",
    "read_number(\"abc\")"
   ],
   "id": "t06-021"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Block | Runs when | Typical use |\n",
    "| --- | --- | --- |\n",
    "| `try` | always (until an error happens) | the code that may fail |\n",
    "| `except` | an error of that type happened | a message, a default value |\n",
    "| `else` | no error happened | the work that needs the result of `try` |\n",
    "| `finally` | always | a final message, cleaning up |\n",
    "\n",
    "Only `try` and `except` are required. The order is fixed: `try`, `except`, `else`, `finally`.\n",
    "\n",
    "### 4.1 Why `else`?\n",
    "\n",
    "Code in `else` is not protected by the `except` blocks. This keeps the `try` block small: only the risky line is inside it.\n",
    "\n",
    "Change it and run: change `\"8\"` to `\"eight\"`."
   ],
   "id": "t06-022"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text = \"8\"\n",
    "try:\n",
    "    number = int(text)\n",
    "except ValueError:\n",
    "    print(\"Not a number\")\n",
    "else:\n",
    "    print(\"Half:\", number / 2)\n",
    "    print(\"Double:\", number * 2)"
   ],
   "id": "t06-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2 `finally` runs even when the error is not caught\n",
    "\n",
    "```python\n",
    "try:\n",
    "    print(10 / 0)\n",
    "finally:\n",
    "    print(\"This is printed before the program stops\")\n",
    "```\n",
    "\n",
    "```\n",
    "This is printed before the program stops\n",
    "ZeroDivisionError: division by zero\n",
    "```\n",
    "\n",
    "## 5. `try` in loops and functions\n",
    "\n",
    "### 5.1 Asking until the input is valid\n",
    "\n",
    "Change it and run: type your own answers in the input box, one per line, with a valid number last.\n",
    "\n",
    "When the cell asks for input, type `abc`, then `20.5`, then `20`."
   ],
   "id": "t06-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "abc",
      "20.5",
      "20"
     ]
    }
   },
   "outputs": [],
   "source": [
    "while True:\n",
    "    text = input(\"Enter your age: \")\n",
    "    try:\n",
    "        age = int(text)\n",
    "        break\n",
    "    except ValueError:\n",
    "        print(\"Please type a whole number\")\n",
    "\n",
    "print(\"Next year you will be\", age + 1)"
   ],
   "id": "t06-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`break` runs only when `int(text)` worked. After an error, the loop asks again.\n",
    "\n",
    "### 5.2 Skipping the bad values of a list\n",
    "\n",
    "The `try` goes inside the loop, so one bad value does not stop the others:\n",
    "\n",
    "Change it and run: add two more bad values to the list."
   ],
   "id": "t06-026"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [\"10\", \"abc\", \"30\", \"\", \"5\"]\n",
    "total = 0\n",
    "skipped = 0\n",
    "\n",
    "for value in values:\n",
    "    try:\n",
    "        total = total + int(value)\n",
    "    except ValueError:\n",
    "        skipped = skipped + 1\n",
    "\n",
    "print(\"Total:\", total)\n",
    "print(\"Skipped:\", skipped)"
   ],
   "id": "t06-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Compare with a `try` around the loop: the first bad value ends the whole loop.\n",
    "\n",
    "Change it and run: move `\"abc\"` to the end of the list. What is the total now?"
   ],
   "id": "t06-028"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [\"10\", \"abc\", \"30\", \"\", \"5\"]\n",
    "total = 0\n",
    "\n",
    "try:\n",
    "    for value in values:\n",
    "        total = total + int(value)\n",
    "except ValueError:\n",
    "    print(\"Stopped at a bad value\")\n",
    "\n",
    "print(\"Total:\", total)"
   ],
   "id": "t06-029"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Where is the `try`? | A bad value | Result |\n",
    "| --- | --- | --- |\n",
    "| inside the loop | that one value is skipped | the loop goes on with the next value |\n",
    "| around the loop | the loop ends | the values after it are never processed |\n",
    "\n",
    "### 5.3 A function that returns a default\n",
    "\n",
    "Change it and run: call `to_number(\"12.5\", 99)`."
   ],
   "id": "t06-030"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def to_number(text, default=0):\n",
    "    try:\n",
    "        return int(text)\n",
    "    except ValueError:\n",
    "        return default\n",
    "\n",
    "print(to_number(\"42\"))\n",
    "print(to_number(\"abc\"))\n",
    "print(to_number(\"abc\", -1))"
   ],
   "id": "t06-031"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.4 An error travels up through function calls\n",
    "\n",
    "If a function does not handle an error, the error goes to the place that called the function. It can be caught there:\n",
    "\n",
    "Change it and run: add a call `show_half(\"10\")`."
   ],
   "id": "t06-032"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def half(text):\n",
    "    return int(text) / 2\n",
    "\n",
    "def show_half(text):\n",
    "    try:\n",
    "        print(half(text))\n",
    "    except ValueError:\n",
    "        print(\"Cannot use\", text)\n",
    "\n",
    "show_half(\"8\")\n",
    "show_half(\"abc\")"
   ],
   "id": "t06-033"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The error happened inside `half`, but `half` has no `try`. So it travelled to `show_half`, which caught it. If nobody catches it, the program stops.\n",
    "\n",
    "## 6. Raising your own errors\n",
    "\n",
    "### 6.1 `raise`\n",
    "\n",
    "Sometimes you decide that a value is wrong, even if Python has no problem with it. `raise` creates an error with your own message:\n",
    "\n",
    "```python\n",
    "def set_age(age):\n",
    "    if age < 0:\n",
    "        raise ValueError(\"Age cannot be negative\")\n",
    "    return age\n",
    "\n",
    "print(set_age(20))\n",
    "print(set_age(-5))\n",
    "```\n",
    "\n",
    "```\n",
    "20\n",
    "ValueError: Age cannot be negative\n",
    "```\n",
    "\n",
    "### 6.2 Catching an error that you raised\n",
    "\n",
    "It is caught like any other error:\n",
    "\n",
    "Change it and run: call `set_age(30)` inside the `try` and print the result."
   ],
   "id": "t06-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def set_age(age):\n",
    "    if age < 0:\n",
    "        raise ValueError(\"Age cannot be negative\")\n",
    "    return age\n",
    "\n",
    "try:\n",
    "    set_age(-5)\n",
    "except ValueError as error:\n",
    "    print(\"Problem:\", error)"
   ],
   "id": "t06-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.3 Choosing the type\n",
    "\n",
    "Use the type that describes the problem:\n",
    "\n",
    "| Problem | Type to raise |\n",
    "| --- | --- |\n",
    "| the value is not acceptable (negative age, empty name) | `ValueError` |\n",
    "| the type is wrong (text where a number is needed) | `TypeError` |\n",
    "\n",
    "Change it and run: add `[10]` to the list of test values."
   ],
   "id": "t06-036"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def average(numbers):\n",
    "    if not isinstance(numbers, list):\n",
    "        raise TypeError(\"numbers must be a list\")\n",
    "    if len(numbers) == 0:\n",
    "        raise ValueError(\"the list is empty\")\n",
    "    return sum(numbers) / len(numbers)\n",
    "\n",
    "for data in [[4, 6], [], \"46\"]:\n",
    "    try:\n",
    "        print(average(data))\n",
    "    except (TypeError, ValueError) as error:\n",
    "        print(type(error).__name__, \"-\", error)"
   ],
   "id": "t06-037"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.4 Why raise instead of printing?\n",
    "\n",
    "A function that only prints a message cannot tell its caller that something went wrong. A function that raises lets the caller decide what to do: show a message, ask again, or use a default.\n",
    "\n",
    "### 6.5 Check first, or try?\n",
    "\n",
    "Both ways are correct:\n",
    "\n",
    "Change it and run: change `\"kiwi\"` to `\"apple\"` in all three places."
   ],
   "id": "t06-038"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5}\n",
    "\n",
    "if \"kiwi\" in prices:\n",
    "    print(prices[\"kiwi\"])\n",
    "else:\n",
    "    print(\"No such product\")\n",
    "\n",
    "try:\n",
    "    print(prices[\"kiwi\"])\n",
    "except KeyError:\n",
    "    print(\"No such product\")"
   ],
   "id": "t06-039"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Use `if` when | Use `try` when |\n",
    "| --- | --- |\n",
    "| the check is simple: `key in d`, `b != 0`, `len(items) > 0` | you cannot know before you try: is this text a number? |\n",
    "| the problem is a normal, frequent case | the problem is rare |\n",
    "\n",
    "Good habits\n",
    "\n",
    "- Keep the `try` block small: only the lines that may fail.\n",
    "- Name the error type.\n",
    "- Do not use `try` to hide mistakes in your own code. Fix them.\n",
    "- Write a message that helps the user: what was wrong and what to do.\n",
    "\n",
    "## 7. File basics\n",
    "\n",
    "Variables are gone when the program ends. A file keeps data on the disk. This part shows only the basics of text files.\n",
    "\n",
    "### 7.1 Writing\n",
    "\n",
    "Change it and run: add a third line to the file."
   ],
   "id": "t06-040"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"notes.txt\", \"w\") as file:\n",
    "    file.write(\"first line\\n\")\n",
    "    file.write(\"second line\\n\")\n",
    "print(\"Saved\")"
   ],
   "id": "t06-041"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `open(\"notes.txt\", \"w\")` opens the file for writing. If it does not exist, Python creates it, in the same folder as the program.\n",
    "- `with` closes the file by itself when the block ends.\n",
    "- `write` takes only text, and it does not start a new line by itself: add `\\n` at the end of each line. Convert numbers with `str()`.\n",
    "\n",
    "### 7.2 Reading\n",
    "\n",
    "Every example that reads a file first creates it, so each example works on its own."
   ],
   "id": "t06-042"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"notes.txt\", \"w\") as file:\n",
    "    file.write(\"first line\\nsecond line\\n\")\n",
    "\n",
    "with open(\"notes.txt\") as file:\n",
    "    text = file.read()\n",
    "print(text)"
   ],
   "id": "t06-043"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`read()` gives the whole file as one text. A `for` loop gives one line at a time. Each line ends with `\\n`, and `.strip()` removes it:\n",
    "\n",
    "Change it and run: remove `.strip()`. Where do the empty lines come from?"
   ],
   "id": "t06-044"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"notes.txt\", \"w\") as file:\n",
    "    file.write(\"first line\\nsecond line\\n\")\n",
    "\n",
    "with open(\"notes.txt\") as file:\n",
    "    for line in file:\n",
    "        print(line.strip())"
   ],
   "id": "t06-045"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A file contains text, so numbers must be converted with `int()` or `float()`:\n",
    "\n",
    "Change it and run: add a fourth number to the file."
   ],
   "id": "t06-046"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"numbers.txt\", \"w\") as file:\n",
    "    file.write(\"10\\n20\\n30\\n\")\n",
    "\n",
    "total = 0\n",
    "with open(\"numbers.txt\") as file:\n",
    "    for line in file:\n",
    "        total = total + int(line)\n",
    "print(total)"
   ],
   "id": "t06-047"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.3 Modes\n",
    "\n",
    "| Mode | Meaning | If the file exists | If the file does not exist |\n",
    "| --- | --- | --- | --- |\n",
    "| `\"r\"` | read (the default) | reads it | `FileNotFoundError` |\n",
    "| `\"w\"` | write | erases it, then writes | creates it |\n",
    "| `\"a\"` | append | keeps it, writes at the end | creates it |\n",
    "\n",
    "Change it and run: change `\"a\"` to `\"w\"`. Which line is lost?"
   ],
   "id": "t06-048"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"log.txt\", \"w\") as file:\n",
    "    file.write(\"Monday\\n\")\n",
    "\n",
    "with open(\"log.txt\", \"a\") as file:\n",
    "    file.write(\"Tuesday\\n\")\n",
    "\n",
    "with open(\"log.txt\") as file:\n",
    "    print(file.read())"
   ],
   "id": "t06-049"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Common mistakes\n",
    "\n",
    "The red text is the real message Python shows. Where there is no message, the program runs but does the wrong thing: the comment shows what it prints.\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "| --- | --- | --- |\n",
    "| `except:` without a type | real mistakes are hidden | name the type: `except ValueError:` |\n",
    "| Catching the wrong type | the error is not caught | read the last line of the message for the type |\n",
    "| Too much code inside `try` | you do not know which line failed | keep only the risky lines in `try` |\n",
    "| `try` around the loop instead of inside it | the first bad value ends the loop | put `try` inside the loop |\n",
    "| `except Exception` before a specific type | the specific block never runs | specific types first |\n",
    "| An empty reaction (`pass`) | the error disappears silently | print a message or use a default |\n",
    "| Using a variable that was never set because of the error | `NameError` later | give it a default in `except` |\n",
    "| Printing in a function instead of raising | the caller cannot react | `raise ValueError(\"...\")` |\n",
    "| Opening an existing file with `\"w\"` | the old content is erased | use `\"a\"` to add |\n",
    "| Forgetting `\\n` or `.strip()` with files | one long line, or empty lines when printing | `\\n` when writing, `strip()` when reading |\n",
    "\n",
    "A variable that was never set:\n",
    "\n",
    "```python\n",
    "try:\n",
    "    amount = int(\"abc\")\n",
    "except ValueError:\n",
    "    print(\"Not a number\")\n",
    "\n",
    "print(amount)\n",
    "```\n",
    "\n",
    "```\n",
    "Not a number\n",
    "NameError: name 'amount' is not defined\n",
    "```\n",
    "\n",
    "`amount` was never created, because the error happened before the assignment finished. Give it a default in the `except` block.\n",
    "\n",
    "## 9. Solved problems (easy to medium-hard)\n",
    "\n",
    "Every example was run, and the outputs are real.\n",
    "\n",
    "### 9.1 Level 1: Easy\n",
    "\n",
    "Problem 1. A safe conversion\n",
    "\n",
    "Change it and run: type `abc`, then `3.5`.\n",
    "\n",
    "When the cell asks for input, type `21`."
   ],
   "id": "t06-050"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "21"
     ]
    }
   },
   "outputs": [],
   "source": [
    "text = input()\n",
    "try:\n",
    "    number = int(text)\n",
    "    print(number * 2)\n",
    "except ValueError:\n",
    "    print(\"not a number\")"
   ],
   "id": "t06-051"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. A safe division"
   ],
   "id": "t06-052"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 10\n",
    "b = 0\n",
    "try:\n",
    "    print(a / b)\n",
    "except ZeroDivisionError:\n",
    "    print(\"cannot divide by zero\")"
   ],
   "id": "t06-053"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 3. A safe list index"
   ],
   "id": "t06-054"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "items = [\"a\", \"b\", \"c\"]\n",
    "index = 5\n",
    "try:\n",
    "    print(items[index])\n",
    "except IndexError:\n",
    "    print(\"no such index\")"
   ],
   "id": "t06-055"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. A safe dictionary lookup, with the message"
   ],
   "id": "t06-056"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = {\"apple\": 1.5, \"bread\": 0.8}\n",
    "try:\n",
    "    print(prices[\"milk\"])\n",
    "except KeyError as error:\n",
    "    print(\"Missing key:\", error)"
   ],
   "id": "t06-057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. Save and read three lines"
   ],
   "id": "t06-058"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"cities.txt\", \"w\") as file:\n",
    "    file.write(\"Baku\\nGanja\\nSheki\\n\")\n",
    "\n",
    "with open(\"cities.txt\") as file:\n",
    "    for line in file:\n",
    "        print(line.strip())"
   ],
   "id": "t06-059"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9.2 Level 2: Medium\n",
    "\n",
    "Problem 6. A division that cannot crash\n",
    "\n",
    "Change it and run: type `10 4`, then `ten 4`.\n",
    "\n",
    "When the cell asks for input, type `10 0`."
   ],
   "id": "t06-060"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "10 0"
     ]
    }
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    a, b = map(int, input().split())\n",
    "    print(a / b)\n",
    "except ValueError:\n",
    "    print(\"Please type two whole numbers\")\n",
    "except ZeroDivisionError:\n",
    "    print(\"Cannot divide by zero\")"
   ],
   "id": "t06-061"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two different things can go wrong, so there are two `except` blocks.\n",
    "\n",
    "Problem 7. Ask until the number is between 1 and 10\n",
    "\n",
    "Change it and run: type your own answers, one per line.\n",
    "\n",
    "When the cell asks for input, type `abc`, then `15`, then `7`."
   ],
   "id": "t06-062"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "abc",
      "15",
      "7"
     ]
    }
   },
   "outputs": [],
   "source": [
    "while True:\n",
    "    try:\n",
    "        number = int(input(\"A number from 1 to 10: \"))\n",
    "    except ValueError:\n",
    "        print(\"That is not a whole number\")\n",
    "        continue\n",
    "    if 1 <= number <= 10:\n",
    "        break\n",
    "    print(\"Out of range\")\n",
    "\n",
    "print(\"Thank you:\", number)"
   ],
   "id": "t06-063"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `try` handles text that is not a number, and the `if` handles a number that is out of range. `continue` goes back to the start of the loop.\n",
    "\n",
    "Problem 8. The sum of the valid numbers"
   ],
   "id": "t06-064"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "values = [\"12\", \"x\", \"7.5\", \"30\", \"-4\"]\n",
    "numbers = []\n",
    "for value in values:\n",
    "    try:\n",
    "        numbers.append(int(value))\n",
    "    except ValueError:\n",
    "        print(\"Skipped:\", value)\n",
    "\n",
    "print(numbers)\n",
    "print(\"Sum:\", sum(numbers))"
   ],
   "id": "t06-065"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `int(\"7.5\")` is a `ValueError` too, because the text is not a whole number.\n",
    "\n",
    "Problem 9. `else` and `finally` together"
   ],
   "id": "t06-066"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def check(text):\n",
    "    try:\n",
    "        number = float(text)\n",
    "    except ValueError:\n",
    "        print(text, \"-> not a number\")\n",
    "    else:\n",
    "        print(text, \"-> half is\", number / 2)\n",
    "    finally:\n",
    "        print(\"checked\", text)\n",
    "\n",
    "check(\"9\")\n",
    "check(\"nine\")"
   ],
   "id": "t06-067"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 10. The sum of the numbers in a file"
   ],
   "id": "t06-068"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"numbers.txt\", \"w\") as file:\n",
    "    file.write(\"12\\n7\\n30\\n11\\n\")\n",
    "\n",
    "with open(\"numbers.txt\") as file:\n",
    "    numbers = [int(line) for line in file]\n",
    "\n",
    "print(numbers)\n",
    "print(\"Sum:\", sum(numbers))"
   ],
   "id": "t06-069"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 11. A calculator that reports every problem\n",
    "\n",
    "Change it and run: add `print(calculate(\"x\", \"+\", \"2\"))`."
   ],
   "id": "t06-070"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calculate(a, operator, b):\n",
    "    try:\n",
    "        a = float(a)\n",
    "        b = float(b)\n",
    "        if operator == \"+\":\n",
    "            return a + b\n",
    "        if operator == \"/\":\n",
    "            return a / b\n",
    "        raise ValueError(f\"unknown operator {operator}\")\n",
    "    except ZeroDivisionError:\n",
    "        return \"error: division by zero\"\n",
    "    except ValueError as error:\n",
    "        return f\"error: {error}\"\n",
    "\n",
    "print(calculate(\"8\", \"+\", \"2\"))\n",
    "print(calculate(\"8\", \"/\", \"0\"))\n",
    "print(calculate(\"8\", \"/\", \"two\"))\n",
    "print(calculate(\"8\", \"%\", \"2\"))"
   ],
   "id": "t06-071"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the unknown operator is our own `ValueError`, raised with `raise`. It is caught by the same block as the conversion error, and the message shows which one it was.\n",
    "\n",
    "Problem 12. A function that checks its argument\n",
    "\n",
    "Change it and run: test a password of your own."
   ],
   "id": "t06-072"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def check_password(password):\n",
    "    if len(password) < 8:\n",
    "        raise ValueError(\"the password needs at least 8 characters\")\n",
    "    if password.isdigit():\n",
    "        raise ValueError(\"the password cannot be only digits\")\n",
    "    return True\n",
    "\n",
    "for password in [\"abc\", \"12345678\", \"python2026\"]:\n",
    "    try:\n",
    "        check_password(password)\n",
    "        print(password, \"-> accepted\")\n",
    "    except ValueError as error:\n",
    "        print(password, \"->\", error)"
   ],
   "id": "t06-073"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 13. An error caught by the caller"
   ],
   "id": "t06-074"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def percent(part, whole):\n",
    "    return part / whole * 100\n",
    "\n",
    "def report(name, part, whole):\n",
    "    try:\n",
    "        print(name, round(percent(part, whole), 1))\n",
    "    except ZeroDivisionError:\n",
    "        print(name, \"no data\")\n",
    "\n",
    "report(\"Aylin\", 17, 20)\n",
    "report(\"Murad\", 0, 0)"
   ],
   "id": "t06-075"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `percent` stays simple and does not handle anything. The error travels to `report`, which knows what to print.\n",
    "\n",
    "Problem 14. Grades with bad records\n",
    "\n",
    "Change it and run: add the record `\"Nigar 77\"`."
   ],
   "id": "t06-076"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "records = [\"Aylin 85\", \"Murad ninety\", \"Leyla\", \"Kamran 45\"]\n",
    "grades = {}\n",
    "problems = []\n",
    "\n",
    "for record in records:\n",
    "    try:\n",
    "        name, grade = record.split()\n",
    "        grades[name] = int(grade)\n",
    "    except ValueError:\n",
    "        problems.append(record)\n",
    "\n",
    "print(grades)\n",
    "print(\"Bad records:\", problems)"
   ],
   "id": "t06-077"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two different problems give the same error type. `int(\"ninety\")` is a `ValueError`, and a record with only one word cannot be unpacked into two variables, which is a `ValueError` too.\n",
    "\n",
    "Problem 15. A log that grows"
   ],
   "id": "t06-078"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"log.txt\", \"w\") as file:\n",
    "    file.write(\"program started\\n\")\n",
    "\n",
    "def add_entry(text):\n",
    "    with open(\"log.txt\", \"a\") as file:\n",
    "        file.write(text + \"\\n\")\n",
    "\n",
    "add_entry(\"user logged in\")\n",
    "add_entry(\"user logged out\")\n",
    "\n",
    "with open(\"log.txt\") as file:\n",
    "    entries = [line.strip() for line in file]\n",
    "print(len(entries), \"entries\")\n",
    "print(\"Last:\", entries[-1])"
   ],
   "id": "t06-079"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the function opens the file with `\"a\"`, so every call adds one line at the end.\n",
    "\n",
    "## 12. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| Exception | an error while the program runs | `ValueError`, `KeyError`, `ZeroDivisionError` |\n",
    "| `try` / `except` | handles an error instead of stopping | `except ValueError:` |\n",
    "| Several types | one block each, or a tuple | `except (ValueError, KeyError):` |\n",
    "| `as error` | gives access to the message | `except ValueError as error:` |\n",
    "| `Exception` | almost every error, as the last block | `except Exception as error:` |\n",
    "| `else` | runs if no error happened | `else: print(number)` |\n",
    "| `finally` | runs always | `finally: print(\"done\")` |\n",
    "| `try` in a loop | one bad value does not stop the others | `for v in values: try: ...` |\n",
    "| `raise` | creates an error yourself | `raise ValueError(\"too short\")` |\n",
    "| `with open(name, mode)` | opens a file and closes it by itself | `with open(\"a.txt\", \"w\") as file:` |\n",
    "| `\"r\"` / `\"w\"` / `\"a\"` | read / write (erases) / append | `open(\"log.txt\", \"a\")` |\n",
    "| `write` / `read` | text into a file / the whole file | `file.write(\"hi\\n\")`, `file.read()` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. Read the last line of an error message first: the type, then the explanation.\n",
    "2. Name the error type in `except`. Never use `except:` alone.\n",
    "3. Keep only the risky lines inside `try`.\n",
    "4. In a loop, put `try` inside it.\n",
    "5. Specific types first, `Exception` last, and always print its message.\n",
    "6. `raise` an error when a value is not acceptable, instead of only printing.\n",
    "7. Open files with `with`. `\"w\"` erases the old content, `\"a\"` adds.\n",
    "\n",
    "Next: the practice notebook (topic-06-practice.ipynb), then Topic 7: modules and packages, and an introduction to classes and objects."
   ],
   "id": "t06-080"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
