{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "77447a22",
   "metadata": {},
   "source": [
    "# Lesson 04: Scavenger Hunt Activity\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",
    "**Objective:** Split a sentence into a list of individual words.\n",
    "\n",
    "**Given:**\n",
    "```python\n",
    "text = \"Python is awesome!\"\n",
    "```\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)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15f70b88",
   "metadata": {},
   "source": [
    "---\n",
    "## Problem 2: The Dictionary Saver\n",
    "\n",
    "**Objective:** Save a Python dictionary to a file and then load it back.\n",
    "\n",
    "**Given:**\n",
    "```python\n",
    "student_data = {\n",
    "    'name': 'Alice',\n",
    "    'age': 22,\n",
    "    'courses': ['Python', 'Data Science', 'Machine Learning'],\n",
    "    'grade': 'A'\n",
    "}\n",
    "```\n",
    "\n",
    "**Your Task:**\n",
    "1. Save the `student_data` dictionary to a file called\n",
    "2. Load the data back from the file into a new ictionary 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. thon"
   ]
  },
  {
   "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)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83f75ce5",
   "metadata": {},
   "source": [
    "### Solution 2: Pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "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)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e45715de",
   "metadata": {},
   "source": [
    "---\n",
    "## Problem 3: The Safe List Accessor\n",
    "\n",
    "**Objective:** Write a function that safely retrieves an element from a list without causing an `IndexError`.\n",
    "\n",
    "**Given:**\n",
    "```python\n",
    "my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']\n",
    "```\n",
    "\n",
    "**Your Task:**\n",
    "1. Create a function called `safe_get(my_list, index, default=None)` that:\n",
    "   - Takes a list, an index, and an optional default value\n",
    "   - Returns the element at the specified index if it exists\n",
    "   - Returns the default value (or `None`) if the index is out of range\n",
    "   - Does NOT raise an `IndexError`\n",
    "2. Test your function with both valid and invalid indices\n",
    "\n",
    "**Test Cases:**\n",
    "- `safe_get(my_list, 2)` → should return `'cherry'`\n",
    "- `safe_get(my_list, 10)` → should return `None`\n",
    "- `safe_get(my_list, -1)` → should return `'elderberry'`\n",
    "- `safe_get(my_list, 100, 'Not found')` → should return `'Not found'`\n",
    "\n",
    "**Hint:** Remember the error handling techniques from the demo notebook!"
   ]
  },
  {
   "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",
    "def safe_get(my_list, index, default=None):\n",
    "    \"\"\"\n",
    "    Safely retrieves an element from a list without raising IndexError.\n",
    "    \n",
    "    Args:\n",
    "        my_list (list): The list to access\n",
    "        index (int): The index to retrieve\n",
    "        default: The value to return if index is out of range (default: None)\n",
    "    \n",
    "    Returns:\n",
    "        The element at the index, or the default value if out of range\n",
    "    \"\"\"\n",
    "    try:\n",
    "        return my_list[index]\n",
    "\n",
    "    except IndexError:\n",
    "        return default\n",
    "\n",
    "# Test cases\n",
    "my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']\n",
    "\n",
    "print(\"Test 1:\", safe_get(my_list, 2))\n",
    "print(\"Test 2:\", safe_get(my_list, 10))\n",
    "print(\"Test 3:\", safe_get(my_list, -1))\n",
    "print(\"Test 4:\", safe_get(my_list, 100, 'Not found'))"
   ]
  },
  {
   "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: The Missing Quotes\n",
    "```python\n",
    "print(Hello, World!)\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: The Indentation Problem\n",
    "```python\n",
    "def greet(name):\n",
    "print(f\"Hello, {name}!\")\n",
    "return \"Greeting complete\"\n",
    "```\n",
    "**Expected Behavior:** Function should print a greeting and return the message"
   ]
  },
  {
   "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: Missing indentation - function body must be indented\n",
    "\n",
    "def greet(name):\n",
    "    print(f\"Hello, {name}!\")\n",
    "    return \"Greeting complete\"\n",
    "\n",
    "# Test it\n",
    "result = greet(\"Student\")\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28bbe6fa",
   "metadata": {},
   "source": [
    "### Bug 3: The Division Disaster\n",
    "```python\n",
    "def calculate_average(numbers):\n",
    "    total = sum(numbers)\n",
    "    average = total / len(numbers)\n",
    "    return average\n",
    "\n",
    "scores = []\n",
    "result = calculate_average(scores)\n",
    "print(f\"Average: {result}\")\n",
    "```\n",
    "**Expected Behavior:** Should handle empty lists gracefully without crashing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "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 if list has elements\n",
    "\n",
    "def calculate_average(numbers):\n",
    "    if len(numbers) == 0:\n",
    "        return 0  # or return None, or raise a custom error\n",
    "\n",
    "    total = sum(numbers)\n",
    "    average = total / len(numbers)\n",
    "\n",
    "    return average\n",
    "\n",
    "# Test with empty list\n",
    "scores = []\n",
    "result = calculate_average(scores)\n",
    "print(f\"Average: {result}\")\n",
    "\n",
    "# Test with numbers\n",
    "scores = [85, 90, 78, 92, 88]\n",
    "result = calculate_average(scores)\n",
    "print(f\"Average: {result}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77e65c8a",
   "metadata": {},
   "source": [
    "### Bug 4: The Type Trouble\n",
    "```python\n",
    "age = input(\"Enter your age: \")\n",
    "next_year_age = age + 1\n",
    "print(f\"Next year you will be {next_year_age}\")\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 25\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}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4eadcbb3",
   "metadata": {},
   "source": [
    "### Bug 5: The List Mystery\n",
    "```python\n",
    "fruits = ['apple', 'banana', 'cherry']\n",
    "print(f\"The fourth fruit is: {fruits[3]}\")\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!\")"
   ]
  },
  {
   "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?\n",
    "\n",
    "**Write your answers in the markdown cell below:**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cf761bf",
   "metadata": {},
   "source": [
    "### Your Reflections:\n",
    "\n",
    "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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be021ddd",
   "metadata": {},
   "source": [
    "---\n",
    "## Congratulations!\n",
    "\n",
    "You've completed the Lesson 04 Scavenger Hunt! You've practiced:\n",
    "- Researching Python documentation\n",
    "- Exploring new modules and methods\n",
    "- Problem-solving independently\n",
    "- Applying concepts in new contexts\n",
    "\n",
    "These skills are essential for becoming a successful programmer. Keep exploring!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv (3.12.3)",
   "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
}
