Skip to content

Commit 9af4179

Browse files
completed lecture 4
1 parent 800dfa6 commit 9af4179

File tree

98 files changed

+54676
-150
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+54676
-150
lines changed

_freeze/part-03/lecture-functions/execute-results/html.json

Lines changed: 2 additions & 2 deletions
Large diffs are not rendered by default.

_freeze/part-04/lecture-dimensions/execute-results/html.json

Lines changed: 12 additions & 0 deletions
Large diffs are not rendered by default.
68.5 KB
Loading
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"hash": "bab2e8201f7edc60898e997308510ab0",
3+
"result": {
4+
"engine": "jupyter",
5+
"markdown": "---\ntitle: \"Lecture V - Handling Errors\"\nsubtitle: \"Programming with Python\"\nauthor: \"Dr. Tobias Vlćek\"\ninstitute: \"Kühne Logistics University Hamburg - Fall 2024\"\ntitle-slide-attributes:\n data-background-color: \"#FFE0D3\"\n\nexecute:\n echo: true\n\nformat:\n revealjs:\n theme: [default, ../styles.scss]\n transition: slide\n transition-speed: fast\n highlight-style: breezedark\n width: 1260\n height: 840\n slide-number: true\n code-copy: true\n code-link: true\n preview-links: auto\n footer: \" {{< meta title >}} | {{< meta subtitle >}} | {{< meta author >}} | [Home](lecture-errors.qmd)\"\n output-file: lecture-errors-presentation.html\n html:\n theme: litera\n highlight-style: breezedark\n linkcolor: \"#a60000\"\n slide-number: true\n code-copy: true\n code-link: true\n toc: true\n toc-location: right\n pdf: \n documentclass: report\n---\n\n\n# [Quick Recap of the last Lecture]{.flow} {.title} \n\n## Data Structures\n\n- [Newly]{.highlight} introduced data structures:\n - **Tuples**: Ordered, immutable collections\n - **Lists**: Ordered, mutable collections\n - **Sets**: Unordered collections of unique elements\n - **Dictionaries**: Key-value pairs\n\n. . .\n\n::: {#e1ef54cb .cell execution_count=2}\n``` {.python .cell-code}\nlist_example = [1, 2, 3, 4, 5]\nset_example = {1, 2, 3, 4, 5}\ndict_example = {\"a\": 1, \"b\": 2, \"c\": 3}\ntuple_example = (1, 2, 3, 4, 5)\n```\n:::\n\n\n## Operations and Methods\n\n- Each data structure has specific operations and methods:\n - Tuples and Lists: Indexing, slicing, concatenation\n - Sets: Union, intersection, difference\n - Dictionaries: Key-based access, `keys()`, `values()`\n\n. . .\n\n::: {.callout-tip}\n**Comprehensions** for concise creation of these structures are often used in practice to create new data structures from existing ones.\n:::\n\n## I/O and File Handling\n\n- Basic file operations\n - Opening files with `open()`\n - Reading and writing files\n - Using the `with` statement for safer file handling\n\n. . .\n\n::: {.callout-note}\nThis covers the main points from our last lecture on data structures and file handling in Python.\n:::\n\n# [Exceptions]{.flow} {.title} \n\n## What are Exceptions?\n\n- Exceptions are [discovered errors]{.highlight} that occur during the execution\n\n. . . \n\n::: {#6fc2c800 .cell execution_count=3}\n``` {.python .cell-code}\ndef divide_numbers(a, b):\n result = a / b\n return result \n\nprint(divide_numbers(10, 0))\nprint(\"I will not be printed as the program crashed before.\")\n```\n:::\n\n\n. . .\n\n[ZeroDivisionError:]{.errors} division by zero\n\n. . .\n\n:::{.callout-warning}\nUndiscovered errors can be very **hard to debug** and can cause **crashes** and **other issues**.\n:::\n\n## Common Built-in Exceptions I\n\n- `ValueError`: argument of correct type but inappropriate value\n- `TypeError`: function applied to object of inappropriate type\n- `NameError`: raised when a local or global name is not found\n- `IndexError`: raised when a sequence subscript is out of range\n- `KeyError`: raised when a dictionary key is not found\n- `FileNotFoundError`: file or directory not found\n- `ZeroDivisionError`: division or modulo by zero\n\n## Common Built-in Exceptions II\n\n- `AttributeError`: attribute reference or assignment fails\n- `ImportError`: import of a modulefails\n- `SyntaxError`: parser encounters a syntax error\n- `IndentationError`: indentation is not correct\n- `RuntimeError`: error does not fall into any category\n\n. . .\n\n::: {.callout-note}\nThe list of built-in exceptions is even longer, these are just the most common ones. We won't cover the errors listed here in detail, but it is good to be aware of them.\n:::\n\n\n## try-except Blocks\n\n- `try-except` blocks are used to handle exceptions\n- `try` block contains the code that might raise an exception\n- `except` block contains the executed code if an exception occurs\n\n. . .\n\n::: {#42d8e61f .cell output-location='fragment' execution_count=4}\n``` {.python .cell-code}\ndef divide_numbers(a, b):\n try:\n result = a / b\n return result\n except ZeroDivisionError:\n return \"Error: Division by zero is not allowed.\"\n\nprint(divide_numbers(10, 0))\nprint(\"I will be printed as the exception was handled!\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\nError: Division by zero is not allowed.\nI will be printed as the exception was handled!\n```\n:::\n:::\n\n\n# [Raising Exceptions]{.flow} {.title}\n\n## Raising Exceptions\n\n- We can [raise exceptions ourselves]{.highlight} using the `raise` statement\n- It allows us to handle errors in a more controlled manner\n\n. . .\n\n::: {#bc81f0cf .cell execution_count=5}\n``` {.python .cell-code}\ndef validate_age(age):\n if age < 0:\n raise ValueError\n return age\n\nprint(validate_age(25)) # This will print 25\nprint(validate_age(-1)) # This will raise a ValueError\n```\n:::\n\n\n[>Task:]{.task} Try to raise an exception in the function above by passing a string to the `validate_age` function. What happens?\n\n## Raising Exceptions with Custom Messages\n\n- We can also raise exceptions with custom messages \n- This helps to provide more information about the error\n\n. . .\n\n::: {#fee4f5f8 .cell execution_count=6}\n``` {.python .cell-code}\ndef validate_age(age):\n if age < 0:\n raise ValueError(\"Age cannot be negative\")\n return age\n\nprint(validate_age(25)) # This will print 25\nprint(validate_age(-1)) # This will raise a ValueError\n```\n:::\n\n\n. . .\n\n[>Question:]{.question} What do you think the `raise` statement will show now?\n\n# [Assertions]{.flow} {.title}\n\n## What are Assertions?\n\n- Assertions are [statements that check if a condition is true]{.highlight}\n- If the condition is false, an `AssertionError` is raised\n- We could use them to check the results of a calculation\n\n. . .\n\n::: {#fad0a17c .cell execution_count=7}\n``` {.python .cell-code}\nx = 9\ny = 10\nassert x < y, \"x is not smaller than y\"\nassert isinstance(y, float), \"y is not a float\"\n```\n:::\n\n\n. . . \n\n[>Task:]{.task} Try to run the code above and discuss what happens.\n\n## Assertions in Functions\n\n- We can also use assertions in functions to check the results of a calculation\n\ndef divide_numbers(a, b):\n assert b != 0, \"Division by zero is not allowed\"\n return a / b\n\nprint(divide_numbers(10, 0)) # This will raise an AssertionError\n```\n\n# [Debugging]{.flow} {.title}\n\n# [Logging]{.flow} {.title}\n\n# [Regular Expressions]{.flow} {.title}\n\n",
6+
"supporting": [
7+
"lecture-errors_files"
8+
],
9+
"filters": [],
10+
"includes": {}
11+
}
12+
}

0 commit comments

Comments
 (0)