From 45b3b5d07ead562b11aed1064b202cecf2ab707d Mon Sep 17 00:00:00 2001 From: Dmitry Nikolaenko Date: Thu, 26 Feb 2026 17:48:17 +0000 Subject: [PATCH 1/2] Improve advanced string manipulation section - Briefly explained methods of objects in the context of strings - Revised each subsection for better readability - Added a few examples demonstrating exceptions in the context of string manipulation - Modified slide types containing notes to 'skip' for student notebook generation (also outside of string manipulation, but not in classes as it's moved to the end in another issue) --- Intermediate.ipynb | 262 +++++++++++++++++++++++++++++------ Intermediate_full.ipynb | 296 +++++++++++++++++++++++++++++++++------- 2 files changed, 468 insertions(+), 90 deletions(-) diff --git a/Intermediate.ipynb b/Intermediate.ipynb index b83adf6..15dd2b3 100644 --- a/Intermediate.ipynb +++ b/Intermediate.ipynb @@ -4749,6 +4749,62 @@ "# 8. Advanced string manipulation" ] }, + { + "cell_type": "markdown", + "id": "e34aedb6", + "metadata": { + "editable": false, + "slideshow": { + "slide_type": "slide" + }, + "tags": [] + }, + "source": [ + "## String Methods - Working with String Objects" + ] + }, + { + "cell_type": "markdown", + "id": "ffef8f84", + "metadata": { + "editable": false, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "In Python, strings are objects, and objects have **methods** - functions that belong to and operate on that object.\n", + "\n", + "**Syntax**: `string_object.method_name(arguments)`\n", + "\n", + "Key characteristics:\n", + "- Methods are called using _dot notation_: `variable.method()`\n", + "- String methods return a **new string** (strings are immutable)\n", + "- The original string is never modified\n", + "- You must assign the result if you want to keep it\n", + "\n", + "**Example:**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5bd4280", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "text = \"hello world\"\n", + "result = text.upper() # Creates new string\n", + "print(text) # Still \"hello world\" \n", + "print(result) # \"HELLO WORLD\"" + ] + }, { "cell_type": "markdown", "id": "c9016a2e-dee1-4030-a1a0-8e519a84be6f", @@ -4760,10 +4816,11 @@ "tags": [] }, "source": [ - "* Adjusting case\n", - "* Formatting strings\n", - " - _Note_: Modification requires assignment, because these functions return a copy, not modifying the original string\n", - "* Quering the existence, replacing, splitting" + "Common categories of string methods we'll explore:\n", + "- **Finding/searching**: `find()`, `index()`\n", + "- **Checking**: `startswith()`, `endswith()`\n", + "- **Transforming**: `replace()`, `upper()`, `lower()`, `capitalize()`, `strip()`\n", + "- **Splitting/joining**: `split()`, `join()`" ] }, { @@ -4777,10 +4834,22 @@ "tags": [] }, "source": [ - "## Finding values \n", - "* `find()` and `index()` both return index of a substring,\n", - " - `index()` raises a `ValueError` exception when not found (_exception handling_)\n", - " - `find()` returns `-1` when a values was not found\n" + "## Finding/searching string methods" + ] + }, + { + "cell_type": "markdown", + "id": "a4fa9b5b", + "metadata": { + "editable": false, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "These methods help you locate substrings within a string, returning their position or checking for their presence:\n", + "* `index()` - returns `-1` if the substring is not found\n", + "* `find()` - raises a `ValueError` if the substring is not found" ] }, { @@ -4817,6 +4886,19 @@ "print(line.find('wombat'))" ] }, + { + "cell_type": "markdown", + "id": "714fc569", + "metadata": { + "editable": false, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "The key difference is how they handle missing substrings - `find()` returns `-1` while `index()` raises an exception:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -4847,7 +4929,7 @@ "tags": [] }, "source": [ - "## Checking conditions on strings" + "## Checking string methods" ] }, { @@ -4861,7 +4943,9 @@ "tags": [] }, "source": [ - "* Checking whether a string starts or ends a certain way is really common and easy" + "These methods return boolean values (`True` or `False`) to verify if a string matches certain patterns or criteria:\n", + "* `startswith(substring)`\n", + "* `endswith(substring)`" ] }, { @@ -4908,12 +4992,12 @@ "metadata": { "editable": false, "slideshow": { - "slide_type": "slide" + "slide_type": "" }, "tags": [] }, "source": [ - "* The canonical way to search a string (if not interested in the index):" + "The canonical way to search a string (if not interested in the index):" ] }, { @@ -4944,7 +5028,25 @@ "tags": [] }, "source": [ - "## Replacing a value:" + "## Transforming string methods" + ] + }, + { + "cell_type": "markdown", + "id": "80b12b8b", + "metadata": { + "editable": false, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "These methods create modified versions of strings by replacing content, changing case, or removing unwanted characters. _**Remember**: strings are immutable, so these methods always return a new string._\n", + "* `replace(old, new)`\n", + "* `upper()`\n", + "* `lower()`\n", + "* `capitalize()`\n", + "* `strip()`" ] }, { @@ -4966,23 +5068,29 @@ ] }, { - "cell_type": "markdown", - "id": "bb4faee5-8c3f-4919-acbe-1b7b2cf7b700", + "cell_type": "code", + "execution_count": null, + "id": "a95784ad-44fc-4e7c-9b16-caa09fedbc60", "metadata": { - "editable": false, + "editable": true, "slideshow": { - "slide_type": "slide" + "slide_type": "" }, "tags": [] }, + "outputs": [], "source": [ - "## Bring all words to a common case" + "arc_update = \"ThE HAmILton suPERcompUTER is beiNg UPGraded\"\n", + "print(arc_update)\n", + "print(arc_update.upper())\n", + "print(arc_update.title())\n", + "print(arc_update.capitalize())" ] }, { "cell_type": "code", "execution_count": null, - "id": "a95784ad-44fc-4e7c-9b16-caa09fedbc60", + "id": "22763b5f-7576-43c5-a237-925dce9b88aa", "metadata": { "editable": true, "slideshow": { @@ -4992,44 +5100,63 @@ }, "outputs": [], "source": [ - "arc_update = \"ThE HAmILton suPERcompUTER is beiNg UPGraded\"\n", - "print(arc_update)\n", - "print(arc_update.upper())\n", - "print(arc_update.title())\n", - "print(arc_update.capitalize())" + "user_input = \" john.doe@email.com \"\n", + "email = user_input.strip()\n", + "print(f\"Original: '{user_input}'\")\n", + "print(f\"Cleaned: '{email}'\")" ] }, { "cell_type": "markdown", - "id": "7a25cc7f-6040-4c03-ac38-b5f9a7baef41", + "id": "2fd63835", "metadata": { "editable": false, "slideshow": { "slide_type": "slide" - }, - "tags": [] + } }, "source": [ - "## Removing white space" + "These methods work with any string and don't raise exceptions, but you may want to validate the results." ] }, { "cell_type": "code", "execution_count": null, - "id": "22763b5f-7576-43c5-a237-925dce9b88aa", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "" - }, - "tags": [] - }, + "id": "8f1ceba1", + "metadata": {}, "outputs": [], "source": [ - "user_input = \" john.doe@email.com \"\n", - "email = user_input.strip()\n", - "print(f\"Original: '{user_input}'\")\n", - "print(f\"Cleaned: '{email}'\")" + "# Transforming methods don't raise exceptions, but you can validate transformed results\n", + "def process_username(username):\n", + " \"\"\"Process and validate a username.\"\"\"\n", + " if not isinstance(username, str):\n", + " raise TypeError(f\"Username must be a string, got {type(username).__name__}\")\n", + " \n", + " # Transform: strip whitespace and convert to lowercase\n", + " processed = username.strip().lower()\n", + " \n", + " # Validate the result\n", + " if not processed:\n", + " raise ValueError(\"Username cannot be empty after processing\")\n", + " \n", + " if len(processed) < 3:\n", + " raise ValueError(f\"Username must be at least 3 characters, got {len(processed)}\")\n", + " \n", + " return processed\n", + "\n", + "# Valid case\n", + "try:\n", + " result = process_username(\" JohnDoe \")\n", + " print(f\"\u2713 Processed username: '{result}'\")\n", + "except ValueError as e:\n", + " print(f\"Error: {e}\")\n", + "\n", + "# Invalid case\n", + "try:\n", + " result = process_username(\" AB \")\n", + " print(f\"\u2713 Processed username: '{result}'\")\n", + "except ValueError as e:\n", + " print(f\"Error: {e}\")" ] }, { @@ -5043,7 +5170,22 @@ "tags": [] }, "source": [ - "## Extracting/concatenating the individual words or parts" + "## Splitting/joining string methods" + ] + }, + { + "cell_type": "markdown", + "id": "71a4546c", + "metadata": { + "editable": false, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "These methods allow you to break strings apart into lists of substrings, or combine lists of strings into a single string. They're particularly useful for parsing text data or formatting output:\n", + "* `split(separator)` - splits string into a list at each occurrence of separator (defaults to whitespace)\n", + "* `join(iterable)` - joins elements of an iterable into a single string with the string as separator" ] }, { @@ -5079,7 +5221,7 @@ "tags": [] }, "source": [ - "The operation in the other direction is `a_string.join()` where `a_string` is placed between every string of a list" + "The `join` operation is `a_string.join()` where `a_string` is placed between every string of a list" ] }, { @@ -5116,6 +5258,40 @@ "print(\"\\n\".join(line_list))" ] }, + { + "cell_type": "markdown", + "id": "0deaf239", + "metadata": { + "editable": false, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "`join()` will raise a `TypeError` if the iterable contains non-string elements" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "225bdd40", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "flags = [16384,1048576]\n", + "\n", + "for i in range(len(flags)):\n", + " flags_str = \"+\".join(flags[i])\n", + "#flags_str = \"+\".join(str(flag) for flag in flags)\n", + "#print(flags_str)" + ] + }, { "cell_type": "markdown", "id": "a965b5d9-59f4-4ed5-b7e9-89f5f0bcf60f", @@ -5932,7 +6108,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.5" + "version": "3.13.0" } }, "nbformat": 4, diff --git a/Intermediate_full.ipynb b/Intermediate_full.ipynb index 3c33560..7e3148a 100644 --- a/Intermediate_full.ipynb +++ b/Intermediate_full.ipynb @@ -3318,7 +3318,7 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "notes" + "slide_type": "skip" } }, "source": [ @@ -3905,7 +3905,7 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "notes" + "slide_type": "skip" }, "tags": [] }, @@ -3963,7 +3963,7 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "notes" + "slide_type": "skip" }, "tags": [] }, @@ -4035,7 +4035,7 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "notes" + "slide_type": "skip" }, "tags": [] }, @@ -4094,7 +4094,7 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "notes" + "slide_type": "skip" }, "tags": [] }, @@ -4184,7 +4184,7 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "notes" + "slide_type": "skip" }, "tags": [] }, @@ -5148,6 +5148,62 @@ "# 8. Advanced string manipulation" ] }, + { + "cell_type": "markdown", + "id": "e34aedb6", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "slide" + }, + "tags": [] + }, + "source": [ + "## String Methods - Working with String Objects" + ] + }, + { + "cell_type": "markdown", + "id": "ffef8f84", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "In Python, strings are objects, and objects have **methods** - functions that belong to and operate on that object.\n", + "\n", + "**Syntax**: `string_object.method_name(arguments)`\n", + "\n", + "Key characteristics:\n", + "- Methods are called using _dot notation_: `variable.method()`\n", + "- String methods return a **new string** (strings are immutable)\n", + "- The original string is never modified\n", + "- You must assign the result if you want to keep it\n", + "\n", + "**Example:**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5bd4280", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "text = \"hello world\"\n", + "result = text.upper() # Creates new string\n", + "print(text) # Still \"hello world\" \n", + "print(result) # \"HELLO WORLD\"" + ] + }, { "cell_type": "markdown", "id": "c9016a2e-dee1-4030-a1a0-8e519a84be6f", @@ -5159,10 +5215,11 @@ "tags": [] }, "source": [ - "* Adjusting case\n", - "* Formatting strings\n", - " - _Note_: Modification requires assignment, because these functions return a copy, not modifying the original string\n", - "* Quering the existence, replacing, splitting" + "Common categories of string methods we'll explore:\n", + "- **Finding/searching**: `find()`, `index()`\n", + "- **Checking**: `startswith()`, `endswith()`\n", + "- **Transforming**: `replace()`, `upper()`, `lower()`, `capitalize()`, `strip()`\n", + "- **Splitting/joining**: `split()`, `join()`" ] }, { @@ -5176,10 +5233,22 @@ "tags": [] }, "source": [ - "## Finding values \n", - "* `find()` and `index()` both return index of a substring,\n", - " - `index()` raises a `ValueError` exception when not found (_exception handling_)\n", - " - `find()` returns `-1` when a values was not found\n" + "## Finding/searching string methods" + ] + }, + { + "cell_type": "markdown", + "id": "a4fa9b5b", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "These methods help you locate substrings within a string, returning their position or checking for their presence:\n", + "* `index()` - returns `-1` if the substring is not found\n", + "* `find()` - raises a `ValueError` if the substring is not found" ] }, { @@ -5216,6 +5285,19 @@ "print(line.find('wombat'))" ] }, + { + "cell_type": "markdown", + "id": "714fc569", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "The key difference is how they handle missing substrings - `find()` returns `-1` while `index()` raises an exception:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -5246,7 +5328,7 @@ "tags": [] }, "source": [ - "## Checking conditions on strings" + "## Checking string methods" ] }, { @@ -5260,7 +5342,22 @@ "tags": [] }, "source": [ - "* Checking whether a string starts or ends a certain way is really common and easy" + "These methods return boolean values (`True` or `False`) to verify if a string matches certain patterns or criteria:\n", + "* `startswith(substring)`\n", + "* `endswith(substring)`" + ] + }, + { + "cell_type": "markdown", + "id": "6ac1c80f", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "skip" + } + }, + "source": [ + "**Note:** These methods are case-sensitive and never raise exceptions - they simply return `False` if the pattern doesn't match." ] }, { @@ -5307,12 +5404,12 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "slide" + "slide_type": "" }, "tags": [] }, "source": [ - "* The canonical way to search a string (if not interested in the index):" + "The canonical way to search a string (if not interested in the index):" ] }, { @@ -5343,7 +5440,25 @@ "tags": [] }, "source": [ - "## Replacing a value:" + "## Transforming string methods" + ] + }, + { + "cell_type": "markdown", + "id": "80b12b8b", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "These methods create modified versions of strings by replacing content, changing case, or removing unwanted characters. _**Remember**: strings are immutable, so these methods always return a new string._\n", + "* `replace(old, new)`\n", + "* `upper()`\n", + "* `lower()`\n", + "* `capitalize()`\n", + "* `strip()`" ] }, { @@ -5365,23 +5480,29 @@ ] }, { - "cell_type": "markdown", - "id": "bb4faee5-8c3f-4919-acbe-1b7b2cf7b700", + "cell_type": "code", + "execution_count": null, + "id": "a95784ad-44fc-4e7c-9b16-caa09fedbc60", "metadata": { "editable": true, "slideshow": { - "slide_type": "slide" + "slide_type": "" }, "tags": [] }, + "outputs": [], "source": [ - "## Bring all words to a common case" + "arc_update = \"ThE HAmILton suPERcompUTER is beiNg UPGraded\"\n", + "print(arc_update)\n", + "print(arc_update.upper())\n", + "print(arc_update.title())\n", + "print(arc_update.capitalize())" ] }, { "cell_type": "code", "execution_count": null, - "id": "a95784ad-44fc-4e7c-9b16-caa09fedbc60", + "id": "22763b5f-7576-43c5-a237-925dce9b88aa", "metadata": { "editable": true, "slideshow": { @@ -5391,58 +5512,92 @@ }, "outputs": [], "source": [ - "arc_update = \"ThE HAmILton suPERcompUTER is beiNg UPGraded\"\n", - "print(arc_update)\n", - "print(arc_update.upper())\n", - "print(arc_update.title())\n", - "print(arc_update.capitalize())" + "user_input = \" john.doe@email.com \"\n", + "email = user_input.strip()\n", + "print(f\"Original: '{user_input}'\")\n", + "print(f\"Cleaned: '{email}'\")" ] }, { "cell_type": "markdown", - "id": "7a25cc7f-6040-4c03-ac38-b5f9a7baef41", + "id": "2fd63835", "metadata": { "editable": true, "slideshow": { "slide_type": "slide" - }, - "tags": [] + } }, "source": [ - "## Removing white space" + "These methods work with any string and don't raise exceptions, but you may want to validate the results." ] }, { "cell_type": "code", "execution_count": null, - "id": "22763b5f-7576-43c5-a237-925dce9b88aa", + "id": "8f1ceba1", + "metadata": {}, + "outputs": [], + "source": [ + "# Transforming methods don't raise exceptions, but you can validate transformed results\n", + "def process_username(username):\n", + " \"\"\"Process and validate a username.\"\"\"\n", + " if not isinstance(username, str):\n", + " raise TypeError(f\"Username must be a string, got {type(username).__name__}\")\n", + " \n", + " # Transform: strip whitespace and convert to lowercase\n", + " processed = username.strip().lower()\n", + " \n", + " # Validate the result\n", + " if not processed:\n", + " raise ValueError(\"Username cannot be empty after processing\")\n", + " \n", + " if len(processed) < 3:\n", + " raise ValueError(f\"Username must be at least 3 characters, got {len(processed)}\")\n", + " \n", + " return processed\n", + "\n", + "# Valid case\n", + "try:\n", + " result = process_username(\" JohnDoe \")\n", + " print(f\"✓ Processed username: '{result}'\")\n", + "except ValueError as e:\n", + " print(f\"Error: {e}\")\n", + "\n", + "# Invalid case\n", + "try:\n", + " result = process_username(\" AB \")\n", + " print(f\"✓ Processed username: '{result}'\")\n", + "except ValueError as e:\n", + " print(f\"Error: {e}\")" + ] + }, + { + "cell_type": "markdown", + "id": "6cf8076f-8f50-49ae-b558-39336c323880", "metadata": { "editable": true, "slideshow": { - "slide_type": "" + "slide_type": "slide" }, "tags": [] }, - "outputs": [], "source": [ - "user_input = \" john.doe@email.com \"\n", - "email = user_input.strip()\n", - "print(f\"Original: '{user_input}'\")\n", - "print(f\"Cleaned: '{email}'\")" + "## Splitting/joining string methods" ] }, { "cell_type": "markdown", - "id": "6cf8076f-8f50-49ae-b558-39336c323880", + "id": "71a4546c", "metadata": { "editable": true, "slideshow": { - "slide_type": "slide" - }, - "tags": [] + "slide_type": "" + } }, "source": [ - "## Extracting/concatenating the individual words or parts" + "These methods allow you to break strings apart into lists of substrings, or combine lists of strings into a single string. They're particularly useful for parsing text data or formatting output:\n", + "* `split(separator)` - splits string into a list at each occurrence of separator (defaults to whitespace)\n", + "* `join(iterable)` - joins elements of an iterable into a single string with the string as separator" ] }, { @@ -5467,6 +5622,19 @@ "print(line.split('jumped'))" ] }, + { + "cell_type": "markdown", + "id": "b21113ff", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "skip" + } + }, + "source": [ + "**Note**: `split()` never raises an exception" + ] + }, { "cell_type": "markdown", "id": "0b649711-58b1-4174-9277-2a921e6a3b6f", @@ -5478,7 +5646,7 @@ "tags": [] }, "source": [ - "The operation in the other direction is `a_string.join()` where `a_string` is placed between every string of a list" + "The `join` operation is `a_string.join()` where `a_string` is placed between every string of a list" ] }, { @@ -5515,6 +5683,40 @@ "print(\"\\n\".join(line_list))" ] }, + { + "cell_type": "markdown", + "id": "0deaf239", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + } + }, + "source": [ + "`join()` will raise a `TypeError` if the iterable contains non-string elements" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "225bdd40", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [], + "source": [ + "flags = [16384,1048576]\n", + "\n", + "for i in range(len(flags)):\n", + " flags_str = \"+\".join(flags[i])\n", + "#flags_str = \"+\".join(str(flag) for flag in flags)\n", + "#print(flags_str)" + ] + }, { "cell_type": "markdown", "id": "a965b5d9-59f4-4ed5-b7e9-89f5f0bcf60f", @@ -6416,7 +6618,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.5" + "version": "3.13.0" } }, "nbformat": 4, From 8d4fef6177c9cc2ebc58ae81972dc97af068d2c9 Mon Sep 17 00:00:00 2001 From: Dmitry Nikolaenko Date: Mon, 2 Mar 2026 00:46:12 +0000 Subject: [PATCH 2/2] Drop exceptions in advanced string manipulation and restore notes slide type from skip --- Intermediate.ipynb | 123 +----------------------------- Intermediate_full.ipynb | 161 ++++++---------------------------------- 2 files changed, 26 insertions(+), 258 deletions(-) diff --git a/Intermediate.ipynb b/Intermediate.ipynb index 15dd2b3..3ae6b56 100644 --- a/Intermediate.ipynb +++ b/Intermediate.ipynb @@ -4848,8 +4848,8 @@ }, "source": [ "These methods help you locate substrings within a string, returning their position or checking for their presence:\n", - "* `index()` - returns `-1` if the substring is not found\n", - "* `find()` - raises a `ValueError` if the substring is not found" + "* `index()`\n", + "* `find()`" ] }, { @@ -4886,38 +4886,6 @@ "print(line.find('wombat'))" ] }, - { - "cell_type": "markdown", - "id": "714fc569", - "metadata": { - "editable": false, - "slideshow": { - "slide_type": "" - } - }, - "source": [ - "The key difference is how they handle missing substrings - `find()` returns `-1` while `index()` raises an exception:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fc5a28ef-8a31-434a-a653-1662cc274945", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "" - }, - "tags": [] - }, - "outputs": [], - "source": [ - "try:\n", - " print(line.index('wombat'))\n", - "except ValueError:\n", - " print(\"A wombat isn't mentioned in the text\")" - ] - }, { "cell_type": "markdown", "id": "40d4c38b-9a07-4e49-a9b3-003dd13f129d", @@ -5106,59 +5074,6 @@ "print(f\"Cleaned: '{email}'\")" ] }, - { - "cell_type": "markdown", - "id": "2fd63835", - "metadata": { - "editable": false, - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "These methods work with any string and don't raise exceptions, but you may want to validate the results." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8f1ceba1", - "metadata": {}, - "outputs": [], - "source": [ - "# Transforming methods don't raise exceptions, but you can validate transformed results\n", - "def process_username(username):\n", - " \"\"\"Process and validate a username.\"\"\"\n", - " if not isinstance(username, str):\n", - " raise TypeError(f\"Username must be a string, got {type(username).__name__}\")\n", - " \n", - " # Transform: strip whitespace and convert to lowercase\n", - " processed = username.strip().lower()\n", - " \n", - " # Validate the result\n", - " if not processed:\n", - " raise ValueError(\"Username cannot be empty after processing\")\n", - " \n", - " if len(processed) < 3:\n", - " raise ValueError(f\"Username must be at least 3 characters, got {len(processed)}\")\n", - " \n", - " return processed\n", - "\n", - "# Valid case\n", - "try:\n", - " result = process_username(\" JohnDoe \")\n", - " print(f\"\u2713 Processed username: '{result}'\")\n", - "except ValueError as e:\n", - " print(f\"Error: {e}\")\n", - "\n", - "# Invalid case\n", - "try:\n", - " result = process_username(\" AB \")\n", - " print(f\"\u2713 Processed username: '{result}'\")\n", - "except ValueError as e:\n", - " print(f\"Error: {e}\")" - ] - }, { "cell_type": "markdown", "id": "6cf8076f-8f50-49ae-b558-39336c323880", @@ -5258,40 +5173,6 @@ "print(\"\\n\".join(line_list))" ] }, - { - "cell_type": "markdown", - "id": "0deaf239", - "metadata": { - "editable": false, - "slideshow": { - "slide_type": "" - } - }, - "source": [ - "`join()` will raise a `TypeError` if the iterable contains non-string elements" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "225bdd40", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "" - }, - "tags": [] - }, - "outputs": [], - "source": [ - "flags = [16384,1048576]\n", - "\n", - "for i in range(len(flags)):\n", - " flags_str = \"+\".join(flags[i])\n", - "#flags_str = \"+\".join(str(flag) for flag in flags)\n", - "#print(flags_str)" - ] - }, { "cell_type": "markdown", "id": "a965b5d9-59f4-4ed5-b7e9-89f5f0bcf60f", diff --git a/Intermediate_full.ipynb b/Intermediate_full.ipynb index 7e3148a..69aa54e 100644 --- a/Intermediate_full.ipynb +++ b/Intermediate_full.ipynb @@ -3318,11 +3318,13 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "skip" + "slide_type": "notes" } }, "source": [ - "_Note_: the data structure returned by `dict.items()` is of type `dict_items`,\n", + "Speaker notes:\n", + "\n", + "The data structure returned by `dict.items()` is of type `dict_items`,\n", "which is an iterable view object displaying the dictionary’s (key, value) pairs" ] }, @@ -3905,12 +3907,12 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "skip" + "slide_type": "notes" }, "tags": [] }, "source": [ - "Notes:\n", + "Speaker notes:\n", " - We are using indented blocks again\n", " - All statements in the try block will be executed one by one\n", " - If one fails, the interpreter checks whether an except block with a matching exception type exists and execute the code in there\n", @@ -3963,12 +3965,12 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "skip" + "slide_type": "notes" }, "tags": [] }, "source": [ - "Notes:\n", + "Speaker notes:\n", "- Do __not__ write out the function again, modify the original function to look like the result function\n", "- Demonstrate that you can catch the exception with a bare except\n", "- Change the function to use the `ZeroDivisionError` explicitely, to avoid catching errors we do not mean to catch" @@ -4035,12 +4037,12 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "skip" + "slide_type": "notes" }, "tags": [] }, "source": [ - "Notes:\n", + "Speaker notes:\n", "- Do __not__ write out the function again, modify the original function to look like the result function\n", "- Using the from keyword we can add an exception to the error stack.\n", "- This can be used to give additional information, that makes the error source in the input easily traceable" @@ -4094,12 +4096,12 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "skip" + "slide_type": "notes" }, "tags": [] }, "source": [ - "Notes:\n", + "Speaker notes:\n", "- Do __not__ write out the function again, modify the original function to look like the result function\n", "- It is good practice to have these checks early in a function. Nobody likes to be 10h into a script execution to then fail a validation" ] @@ -4184,12 +4186,12 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "skip" + "slide_type": "notes" }, "tags": [] }, "source": [ - "Notes:\n", + "Speaker notes:\n", "- Do __not__ write out the function again, modify the original function to look like the result function\n", "- Finally is often used in clean up operations." ] @@ -4675,7 +4677,7 @@ "tags": [] }, "source": [ - "Speaker notes\n", + "Speaker notes:\n", " - In this example, participants can be contacted via e-mail or Teams\n", " - The information we need for the two contact possibilities is completely independent\n", " - The specific behaviour is used by the class, but the details are not important for the class\n", @@ -5247,8 +5249,8 @@ }, "source": [ "These methods help you locate substrings within a string, returning their position or checking for their presence:\n", - "* `index()` - returns `-1` if the substring is not found\n", - "* `find()` - raises a `ValueError` if the substring is not found" + "* `index()`\n", + "* `find()`" ] }, { @@ -5291,32 +5293,15 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "" + "slide_type": "notes" } }, "source": [ + "Speaker notes:\n", + "\n", "The key difference is how they handle missing substrings - `find()` returns `-1` while `index()` raises an exception:" ] }, - { - "cell_type": "code", - "execution_count": null, - "id": "fc5a28ef-8a31-434a-a653-1662cc274945", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "" - }, - "tags": [] - }, - "outputs": [], - "source": [ - "try:\n", - " print(line.index('wombat'))\n", - "except ValueError:\n", - " print(\"A wombat isn't mentioned in the text\")" - ] - }, { "cell_type": "markdown", "id": "40d4c38b-9a07-4e49-a9b3-003dd13f129d", @@ -5353,11 +5338,13 @@ "metadata": { "editable": true, "slideshow": { - "slide_type": "skip" + "slide_type": "notes" } }, "source": [ - "**Note:** These methods are case-sensitive and never raise exceptions - they simply return `False` if the pattern doesn't match." + "Speaker notes:\n", + "\n", + "These methods are case-sensitive." ] }, { @@ -5518,59 +5505,6 @@ "print(f\"Cleaned: '{email}'\")" ] }, - { - "cell_type": "markdown", - "id": "2fd63835", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "These methods work with any string and don't raise exceptions, but you may want to validate the results." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8f1ceba1", - "metadata": {}, - "outputs": [], - "source": [ - "# Transforming methods don't raise exceptions, but you can validate transformed results\n", - "def process_username(username):\n", - " \"\"\"Process and validate a username.\"\"\"\n", - " if not isinstance(username, str):\n", - " raise TypeError(f\"Username must be a string, got {type(username).__name__}\")\n", - " \n", - " # Transform: strip whitespace and convert to lowercase\n", - " processed = username.strip().lower()\n", - " \n", - " # Validate the result\n", - " if not processed:\n", - " raise ValueError(\"Username cannot be empty after processing\")\n", - " \n", - " if len(processed) < 3:\n", - " raise ValueError(f\"Username must be at least 3 characters, got {len(processed)}\")\n", - " \n", - " return processed\n", - "\n", - "# Valid case\n", - "try:\n", - " result = process_username(\" JohnDoe \")\n", - " print(f\"✓ Processed username: '{result}'\")\n", - "except ValueError as e:\n", - " print(f\"Error: {e}\")\n", - "\n", - "# Invalid case\n", - "try:\n", - " result = process_username(\" AB \")\n", - " print(f\"✓ Processed username: '{result}'\")\n", - "except ValueError as e:\n", - " print(f\"Error: {e}\")" - ] - }, { "cell_type": "markdown", "id": "6cf8076f-8f50-49ae-b558-39336c323880", @@ -5622,19 +5556,6 @@ "print(line.split('jumped'))" ] }, - { - "cell_type": "markdown", - "id": "b21113ff", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "skip" - } - }, - "source": [ - "**Note**: `split()` never raises an exception" - ] - }, { "cell_type": "markdown", "id": "0b649711-58b1-4174-9277-2a921e6a3b6f", @@ -5683,40 +5604,6 @@ "print(\"\\n\".join(line_list))" ] }, - { - "cell_type": "markdown", - "id": "0deaf239", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "" - } - }, - "source": [ - "`join()` will raise a `TypeError` if the iterable contains non-string elements" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "225bdd40", - "metadata": { - "editable": true, - "slideshow": { - "slide_type": "" - }, - "tags": [] - }, - "outputs": [], - "source": [ - "flags = [16384,1048576]\n", - "\n", - "for i in range(len(flags)):\n", - " flags_str = \"+\".join(flags[i])\n", - "#flags_str = \"+\".join(str(flag) for flag in flags)\n", - "#print(flags_str)" - ] - }, { "cell_type": "markdown", "id": "a965b5d9-59f4-4ed5-b7e9-89f5f0bcf60f",