{ "cells": [ { "cell_type": "markdown", "id": "77447a22", "metadata": {}, "source": [ "# Lesson 04 activity solution\n", "\n", "In this activity, you'll solve four problems that build on what you've learned in Lesson 04. However, these problems will require you to **research**, **explore**, and **discover** Python methods and techniques not directly covered in the demonstration notebooks.\n", "\n", "## Instructions:\n", "- Each problem has a clear objective\n", "- You may need to use Google, Python documentation, or experimentation\n", "- Test your solutions in the code cells provided\n", "- There are multiple ways to solve each problem - be creative!" ] }, { "cell_type": "markdown", "id": "68cc8b66", "metadata": {}, "source": [ "---\n", "## Problem 1: The word splitter\n", "\n", "**Your Task:**\n", "- Research string methods that can break a sentence into parts\n", "- Split the string `text` into a list of words and store it in a variable called `word_list`\n", "- Print both the original sentence and the list of words\n", "- Print the number of words in the sentence" ] }, { "cell_type": "code", "execution_count": null, "id": "40496d62", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original sentence: Python is awesome!\n", "List of words: ['Python', 'is', 'awesome!']\n", "Number of words: 3\n" ] } ], "source": [ "# Problem 1: Your solution here\n", "text = 'Python is awesome!'\n", "\n", "# Write your code below\n", "# Using the split() method to break the sentence into words\n", "word_list = text.split()\n", "\n", "# Print the original sentence\n", "print(f'Original sentence: {text}')\n", "\n", "# Print the list of words\n", "print(f'List of words: {word_list}')\n", "\n", "# Print the number of words\n", "print(f'Number of words: {len(word_list)}')\n" ] }, { "cell_type": "markdown", "id": "15f70b88", "metadata": {}, "source": [ "---\n", "## Problem 2: The dictionary saver\n", "\n", "**Your Task:**\n", "1. Save the `student_data` dictionary to a file\n", "2. Load the data back from the file into a new dictionary called `loaded_data`\n", "3. Print both the original and loaded dictionaries to verify they match\n", "4. Use error handling to manage any potential issues\n", "\n", "**Hint:** JSON (JavaScript Object Notation) is a popular format for storing structured data." ] }, { "cell_type": "code", "execution_count": 2, "id": "93e02c6c", "metadata": {}, "outputs": [], "source": [ "# Problem 2: Your solution here\n", "\n", "# Given dictionary\n", "student_data = {\n", " 'name': 'Alice',\n", " 'age': 22,\n", " 'courses': ['Python', 'Data Science', 'Machine Learning'],\n", " 'grade': 'A'\n", "}\n", "\n", "# Write your code below to save and load the dictionary" ] }, { "cell_type": "markdown", "id": "9d934f5d", "metadata": {}, "source": [ "### Solution 1: JSON" ] }, { "cell_type": "code", "execution_count": 3, "id": "9a67266b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Data saved successfully!\n", "\n", "Data loaded successfully!\n", "\n", "Original dictionary:\n", "{'name': 'Alice', 'age': 22, 'courses': ['Python', 'Data Science', 'Machine Learning'], 'grade': 'A'}\n", "\n", "Loaded dictionary:\n", "{'name': 'Alice', 'age': 22, 'courses': ['Python', 'Data Science', 'Machine Learning'], 'grade': 'A'}\n", "\n", "Dictionaries match: True\n" ] } ], "source": [ "import json\n", "\n", "# Save the dictionary to a file\n", "try:\n", " with open('student_data.json', 'w') as file:\n", " json.dump(student_data, file, indent=4)\n", "\n", " print('Data saved successfully!')\n", "\n", "except Exception as e:\n", " print(f'Error saving data: {e}')\n", "\n", "# Load the data back from the file\n", "try:\n", " with open('student_data.json', 'r') as file:\n", " loaded_data = json.load(file)\n", "\n", " print('\\nData loaded successfully!')\n", "\n", "except FileNotFoundError:\n", "\n", " print('Error: File not found!')\n", " loaded_data = None\n", "\n", "except json.JSONDecodeError:\n", "\n", " print('Error: Invalid JSON format!')\n", " loaded_data = None\n", "\n", "except Exception as e:\n", "\n", " print(f'Error loading data: {e}')\n", " loaded_data = None\n", "\n", "# Print both dictionaries to verify\n", "print('\\nOriginal dictionary:')\n", "print(student_data)\n", "print('\\nLoaded dictionary:')\n", "print(loaded_data)\n", "print('\\nDictionaries match:', student_data == loaded_data)\n" ] }, { "cell_type": "markdown", "id": "83f75ce5", "metadata": {}, "source": [ "### Solution 2: Pickle" ] }, { "cell_type": "code", "execution_count": 4, "id": "73a27fa9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Data saved successfully with pickle!\n", "\n", "Data loaded successfully with pickle!\n", "\n", "Original dictionary:\n", "{'name': 'Alice', 'age': 22, 'courses': ['Python', 'Data Science', 'Machine Learning'], 'grade': 'A'}\n", "\n", "Loaded dictionary (from pickle):\n", "{'name': 'Alice', 'age': 22, 'courses': ['Python', 'Data Science', 'Machine Learning'], 'grade': 'A'}\n", "\n", "Dictionaries match: True\n" ] } ], "source": [ "import pickle\n", "\n", "# Save the dictionary to a file using pickle\n", "try:\n", " with open('student_data.pkl', 'wb') as file: # 'wb' = write binary\n", " pickle.dump(student_data, file)\n", "\n", " print('Data saved successfully with pickle!')\n", "\n", "except Exception as e:\n", " print(f'Error saving data: {e}')\n", "\n", "# Load the data back from the file\n", "try:\n", " with open('student_data.pkl', 'rb') as file: # 'rb' = read binary\n", " loaded_data_pickle = pickle.load(file)\n", "\n", " print('\\nData loaded successfully with pickle!')\n", "\n", "except FileNotFoundError:\n", "\n", " print('Error: File not found!')\n", " loaded_data_pickle = None\n", "\n", "except pickle.UnpicklingError:\n", "\n", " print('Error: Invalid pickle format!')\n", " loaded_data_pickle = None\n", "\n", "except Exception as e:\n", "\n", " print(f'Error loading data: {e}')\n", " loaded_data_pickle = None\n", "\n", "# Print both dictionaries to verify\n", "print('\\nOriginal dictionary:')\n", "print(student_data)\n", "print('\\nLoaded dictionary (from pickle):')\n", "print(loaded_data_pickle)\n", "print('\\nDictionaries match:', student_data == loaded_data_pickle)\n" ] }, { "cell_type": "markdown", "id": "e45715de", "metadata": {}, "source": [ "---\n", "## Problem 3: The safe list accessor\n", "\n", "**Your Task:**\n", "1. Use a `try/except` block to access index `2` from `my_list`. Store the result in a variable called `item_2`.\n", "2. Use a `try/except` block to access index `10` from `my_list`. If the index doesn't exist, store `'Not found'` in a variable called `item_10`.\n", "3. Use a `try/except` block to access index `-1` from `my_list`. Store the result in a variable called `item_last`.\n", "4. Print all three variables.\n", "\n", "**Expected output:**\n", "```\n", "Item at index 2: cherry\n", "Item at index 10: Not found\n", "Item at index -1: elderberry\n", "```\n", "\n", "**Hint:** Use `IndexError` in your `except` clause." ] }, { "cell_type": "code", "execution_count": null, "id": "17edfb8a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Test 1: cherry\n", "Test 2: None\n", "Test 3: elderberry\n", "Test 4: Not found\n" ] } ], "source": [ "# Problem 3: Your solution here\n", "\n", "my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']\n", "\n", "# Access index 2 safely\n", "try:\n", " item_2 = my_list[2]\n", "\n", "except IndexError:\n", " item_2 = None\n", "\n", "# Access index 10 safely (store 'Not found' if it doesn't exist)\n", "try:\n", " item_10 = my_list[10]\n", "\n", "except IndexError:\n", " item_10 = 'Not found'\n", "\n", "# Access index -1 safely\n", "try:\n", " item_last = my_list[-1]\n", "\n", "except IndexError:\n", " item_last = None\n", "\n", "print('Item at index 2:', item_2)\n", "print('Item at index 10:', item_10)\n", "print('Item at index -1:', item_last)\n" ] }, { "cell_type": "markdown", "id": "7b030bdf", "metadata": {}, "source": [ "---\n", "## Problem 4: Fixing bugs\n", "\n", "**Objective:** Debug and fix code snippets that contain common Python errors.\n", "\n", "**Your Task:**\n", "Below are several code snippets that contain bugs. For each one:\n", "1. Identify the error\n", "2. Fix the code\n", "3. Test that it works correctly\n", "4. Add a comment explaining what was wrong\n", "\n", "Run each fixed snippet to verify it works!" ] }, { "cell_type": "markdown", "id": "e438028b", "metadata": {}, "source": [ "### Bug 1\n", "\n", "**Expected output:** `Hello, World!`" ] }, { "cell_type": "code", "execution_count": null, "id": "89d1a0c8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, World!\n" ] } ], "source": [ "# Bug 1: Fix the code below\n", "# Error: Missing quotes around the string - Python expects Hello and World to be variables\n", "\n", "print('Hello, World!')" ] }, { "cell_type": "markdown", "id": "29a63bcc", "metadata": {}, "source": [ "### Bug 2\n", "\n", "**Expected behavior:** Should catch the error and print `Error: Cannot divide by zero!` without crashing" ] }, { "cell_type": "code", "execution_count": null, "id": "219901ae", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Student!\n", "Greeting complete\n" ] } ], "source": [ "# Bug 2: Fix the code below\n", "# Error: Wrong exception type - ZeroDivisionError should be caught, not ValueError\n", "\n", "numerator = 10\n", "denominator = 0\n", "\n", "try:\n", " result = numerator / denominator\n", " print(f'Result: {result}')\n", "\n", "except ZeroDivisionError:\n", " print('Error: Cannot divide by zero!')\n" ] }, { "cell_type": "markdown", "id": "28bbe6fa", "metadata": {}, "source": [ "### Bug 3\n", "\n", "**Expected behavior:** Should handle an empty list gracefully without crashing" ] }, { "cell_type": "code", "execution_count": null, "id": "c6a0e1d8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Average: 0\n", "Average: 86.6\n" ] } ], "source": [ "# Bug 3: Fix the code below\n", "# Error: Division by zero when list is empty - need to check before dividing\n", "\n", "scores = []\n", "\n", "if len(scores) == 0:\n", " print('No scores to average!')\n", "\n", "else:\n", " total = sum(scores)\n", " average = total / len(scores)\n", " print(f'Average score: {average}')\n", "\n", "# Test with scores\n", "scores = [85, 90, 78, 92, 88]\n", "total = sum(scores)\n", "average = total / len(scores)\n", "print(f'Average score: {average}')\n" ] }, { "cell_type": "markdown", "id": "77e65c8a", "metadata": {}, "source": [ "### Bug 4\n", "\n", "**Expected behavior:** Should correctly calculate age + 1 (Hint: What type does `input()` return?)" ] }, { "cell_type": "code", "execution_count": 9, "id": "e1ad8f92", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Next year you will be 36\n" ] } ], "source": [ "# Bug 4: Fix the code below\n", "# Error: input() returns a string, not an integer - need to convert to int\n", "\n", "age = input('Enter your age: ')\n", "age = int(age) # Convert string to integer\n", "next_year_age = age + 1\n", "print(f'Next year you will be {next_year_age}')\n" ] }, { "cell_type": "markdown", "id": "4eadcbb3", "metadata": {}, "source": [ "### Bug 5\n", "\n", "**Expected behavior:** Should handle the list access safely or explain why it fails" ] }, { "cell_type": "code", "execution_count": 10, "id": "410029fc", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "There is no fourth fruit. The list only has 3 fruits.\n", "Error: There is no fourth fruit in the list!\n" ] } ], "source": [ "# Bug 5: Fix the code below\n", "# Error: IndexError - list only has 3 elements (indices 0-2), but trying to access index 3\n", "\n", "fruits = ['apple', 'banana', 'cherry']\n", "\n", "# Option 1: Check if index exists\n", "if len(fruits) > 3:\n", " print(f'The fourth fruit is: {fruits[3]}')\n", "\n", "else:\n", " print(f'There is no fourth fruit. The list only has {len(fruits)} fruits.')\n", "\n", "# Option 2: Use try-except\n", "try:\n", " print(f'The fourth fruit is: {fruits[3]}')\n", "\n", "except IndexError:\n", " print(f'Error: There is no fourth fruit in the list!')\n" ] }, { "cell_type": "markdown", "id": "814cfe98", "metadata": {}, "source": [ "---\n", "## __Reflection questions__\n", "\n", "After completing the scavenger hunt, answer these questions:\n", "\n", "1. What resources did you use to find solutions? (Documentation, Stack Overflow, etc.)\n", "2. Which problem was most challenging? Why?\n", "3. What new Python feature or method did you find most interesting?\n", "4. How did you approach debugging when your code didn't work initially?" ] }, { "cell_type": "markdown", "id": "3cf761bf", "metadata": {}, "source": [ "1. **Resources used:** Python official documentation (docs.python.org), particularly for the `json` module and string methods. Also used knowledge of try-except blocks for error handling.\n", "\n", "2. **Most challenging problem:** Problem 2 (Dictionary Saver) was most challenging because it required researching the JSON module, understanding file I/O operations, and implementing comprehensive error handling for multiple potential failure points.\n", "\n", "3. **Most interesting feature:** The `json` module's ability to seamlessly convert Python dictionaries to JSON format and back. It's powerful for data persistence and makes sharing structured data between applications easy.\n", "\n", "4. **Debugging approach:** Used a systematic approach: first identified the error type (SyntaxError, IndentationError, TypeError, IndexError, ZeroDivisionError), then applied the appropriate fix. For complex issues, tested with simple cases first before moving to edge cases.\n" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }