{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "ULxWGdhVqcRt" }, "source": [ "# Chapter 8: Extra Content\n", "\n", "```{image} abertura-light.png\n", ":alt: Horizontal lines that break off at different points and fall until a double rule at the foot catches them\n", ":class: abertura only-light\n", "```\n", "\n", "```{image} abertura-dark.png\n", ":alt: Horizontal lines that break off at different points and fall until a double rule at the foot catches them\n", ":class: abertura only-dark\n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Error Handling (`try/except`)\n", "\n", "In Python, we use the `try/except` block to handle errors that may occur during program execution, preventing it from being interrupted unexpectedly.\n", "\n", "**Basic example with `try/except`:**\n", "\n", "```python\n", "try:\n", " number = int(input(\"Enter a number: \"))\n", " result = 10 / number\n", " print(f\"The result is {result}.\")\n", "except ZeroDivisionError:\n", " print(\"Error: division by zero.\")\n", "except ValueError:\n", " print(\"Error: invalid input.\")\n", "```\n", "\n", "**Output:**\n", "\n", "```\n", "Enter a number: 2\n", "The result is 5.0.\n", "```\n", "\n", "```\n", "Enter a number: 0\n", "Error: division by zero.\n", "```\n", "\n", "```\n", "Enter a number: abc\n", "Error: invalid input.\n", "```\n", "\n", "\n", "### `else` and `finally` blocks in error handling\n", "\n", "In addition to `try` and `except`, Python allows the optional use of `else` and `finally` blocks to make error handling more complete.\n", "\n", "**`else`**\n", "\n", "Executed **only if no error occurs** in the `try` block.\n", "\n", "**`finally`**\n", "\n", "Executed **always**, with or without an error. It is useful for releasing resources, such as closing files or database connections.\n", "\n", "**Example with `else` and `finally`:**\n", "\n", "```python\n", "try:\n", " number = int(input(\"Enter a number: \"))\n", " result = 10 / number\n", "except ZeroDivisionError:\n", " print(\"Error: division by zero.\")\n", "except ValueError:\n", " print(\"Error: invalid input.\")\n", "else:\n", " print(f\"The result is {result}.\")\n", "finally:\n", " print(\"Execution finished.\")\n", "```\n", "\n", "**Output:**\n", "\n", "```\n", "Enter a number: 2\n", "The result is 5.0.\n", "Execution finished.\n", "```\n", "\n", "```\n", "Enter a number: 0\n", "Error: division by zero.\n", "Execution finished.\n", "```\n", "\n", "```\n", "Enter a number: xyz\n", "Error: invalid input.\n", "Execution finished.\n", "```\n", "\n", "\n", "### Using `try/except` in functions\n", "\n", "It is common to use `try/except` inside functions to make them safer and more reusable.\n", "\n", "```python\n", "def divide(a, b):\n", " try:\n", " return a / b\n", " except ZeroDivisionError:\n", " return \"Error: division by zero.\"\n", "\n", "print(divide(10, 2)) # Output: 5.0\n", "print(divide(10, 0)) # Output: Error: division by zero.\n", "```\n", "\n", "**Output:**\n", "\n", "```\n", "5.0\n", "Error: division by zero.\n", "```\n", "\n", "\n", "### Summary Table\n", "\n", "| Block | When it is executed |\n", "| --------- | ------------------------------------------- |\n", "| `try` | Tries to execute code that may error |\n", "| `except` | Executes if an error occurs in the `try` |\n", "| `else` | Executes if **no error** occurs in the `try` |\n", "| `finally` | Always executes, with or without error |\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## File Handling\n", "\n", "So far, our programs' data lived only in memory: as soon as the program ended, everything was lost. To **store** information permanently (a report, a to-do list, settings), we write the data to **files**.\n", "\n", "### Opening a file: the `open()` function\n", "\n", "To work with a file, we first open it with `open()`, giving the **path** and the **mode**:\n", "\n", "```python\n", "file = open(\"data.txt\", \"r\", encoding=\"utf-8\")\n", "```\n", "\n", "