{ "cells": [ { "cell_type": "markdown", "id": "c5793bda", "metadata": {}, "source": [ "# Lesson 06 activity: Functions challenge\n", "\n", "In this activity, you'll solve problems that build on what you've learned about functions in Lesson 06. These problems will require you to **apply function concepts**, **work with different types of parameters**, and **understand variable scope**.\n", "\n", "## Instructions:\n", "- Each problem has a clear objective\n", "- You may need to research, experiment, or combine multiple concepts\n", "- Test your solutions in the code cells provided\n", "- There are multiple ways to solve each problem - be creative!" ] }, { "cell_type": "markdown", "id": "62d9f312", "metadata": {}, "source": [ "---\n", "## Problem 1: The temperature converter\n", "\n", "**Objective:** Create a versatile temperature conversion function with default parameters.\n", "\n", "**Your Task:**\n", "Write a function called `convert_temperature(value, from_unit='C', to_unit='F')` that:\n", "- Converts temperatures between Celsius (C) and Fahrenheit (F)\n", "- Uses default parameters for `from_unit` and `to_unit`\n", "- Returns the converted temperature rounded to 1 decimal place\n", "- Handles invalid unit inputs by returning an error message\n", "\n", "**Conversion formulas:**\n", "- Celsius to Fahrenheit: `(C × 9/5) + 32`\n", "- Fahrenheit to Celsius: `(F - 32) × 5/9`\n", "\n", "**Test cases:**\n", "- `convert_temperature(100)` → 212.0 (default C to F)\n", "- `convert_temperature(32, 'F', 'C')` → 0.0\n", "\n", "**Hints:**\n", "- Use if-elif statements to handle different conversion cases\n", "- Use the `round()` function for the return value" ] }, { "cell_type": "code", "execution_count": null, "id": "5a5ee3ca", "metadata": {}, "outputs": [], "source": [ "# Problem 1: Your solution here\n", "\n", "def convert_temperature(value, from_unit='C', to_unit='F'):\n", " '''\n", " Converts temperature between Celsius and Fahrenheit.\n", "\n", " Args:\n", " value (float): The temperature value to convert\n", " from_unit (str): The unit to convert from ('C' or 'F')\n", " to_unit (str): The unit to convert to ('C' or 'F')\n", " \n", " Returns:\n", " float: The converted temperature rounded to 1 decimal places\n", " '''\n", "\n", " # Write your code here (remove the pass statement)\n", " pass\n", "\n", "# Test cases\n", "print('Test 1:', convert_temperature(100))\n", "print('Test 2:', convert_temperature(32, 'F', 'C'))\n" ] }, { "cell_type": "markdown", "id": "372ddd91", "metadata": {}, "source": [ "---\n", "## Problem 2: The flexible statistics calculator\n", "\n", "**Objective:** Create a function that uses *args to calculate statistics on any number of values.\n", "\n", "**Your Task:**\n", "Write a function called `calculate_stats(*numbers, operation='mean')` that:\n", "- Accepts any number of numeric arguments using `*numbers`\n", "- Has a keyword parameter `operation` with default value `'mean'`\n", "- Supports these operations:\n", " - `'mean'`: Calculate the average\n", " - `'range'`: Calculate max - min\n", " - `'sum'`: Calculate the total\n", "- Returns the calculated result\n", "- Handles edge cases (empty input, invalid operation)\n", "\n", "**Test cases:**\n", "- `calculate_stats(1, 2, 3, 4, 5)` → 3.0 (mean)\n", "- `calculate_stats(10, 20, 30, operation='range')` → 20\n", "- `calculate_stats(5, 10, 15, operation='sum')` → 30\n", "\n", "**Hints:**\n", "- Use `len(numbers)` to check if any numbers were provided\n", "- Python has built-in functions for mean, min, max and sum, you don't need to code the arithmetic yourself!" ] }, { "cell_type": "code", "execution_count": null, "id": "6a682da8", "metadata": {}, "outputs": [], "source": [ "# Problem 2: Your solution here\n", "\n", "def calculate_stats(*numbers, operation='mean'):\n", " '''\n", " Calculates various statistics on a variable number of values.\n", " \n", " Args:\n", " *numbers: Variable number of numeric values\n", " operation (str): The statistical operation to perform\n", " \n", " Returns:\n", " float/int: The calculated statistic\n", " '''\n", "\n", " # Write your code here (remove the pass statement)\n", " pass\n", "\n", "# Test cases\n", "print('Test 1 (mean):', calculate_stats(1, 2, 3, 4, 5))\n", "print('Test 3 (range):', calculate_stats(10, 20, 30, operation='range'))\n", "print('Test 4 (sum):', calculate_stats(5, 10, 15, operation='sum'))\n" ] }, { "cell_type": "markdown", "id": "38aa6de1", "metadata": {}, "source": [ "---\n", "## Problem 3: The text analyzer\n", "\n", "**Objective:** Create a text analysis tool using functions with multiple return values.\n", "\n", "**Your Task:**\n", "Write a function called `analyze_text(text, case_sensitive=False)` that:\n", "- Takes a text string and optional case_sensitive boolean\n", "- Returns a tuple containing:\n", " 1. Total number of words\n", " 2. Total number of characters (excluding spaces)\n", " 3. Number of unique words\n", "- If `case_sensitive=False`, converts text to lowercase for analysis\n", "- Removes punctuation before counting words\n", "\n", "**Expected output:**\n", "- Words: 9\n", "- Characters: 43\n", "- Unique words: 5\n", "\n", "**Hints:**\n", "- Use `.split()` to break text into words\n", "- Use `.replace()` or string methods to remove punctuation\n", "- Read about the `set` data type for finding the number of unique words" ] }, { "cell_type": "code", "execution_count": null, "id": "33b0ef24", "metadata": {}, "outputs": [], "source": [ "# Problem 3: Your solution here\n", "\n", "def analyze_text(text, case_sensitive=False):\n", " '''\n", " Analyzes text and returns various statistics.\n", " \n", " Args:\n", " text (str): The text to analyze\n", " case_sensitive (bool): Whether to treat uppercase and lowercase as different\n", " \n", " Returns:\n", " tuple: (word_count, char_count, unique_words, longest_word, frequencies)\n", " '''\n", "\n", " # Write your code here (remove the pass statement)\n", " pass\n", "\n", "# Test case\n", "text = 'Python is great! Python is powerful. Python is versatile.'\n", "\n", "print('Analyzing text:')\n", "print(f'Text: {text}\\n')\n", "\n", "word_count, char_count, unique_words = analyze_text(text)\n", "\n", "print(f'Total words: {word_count}')\n", "print(f'Total characters (no spaces): {char_count}')\n", "print(f'Unique words: {unique_words}')\n" ] }, { "cell_type": "markdown", "id": "7f61f020", "metadata": {}, "source": [ "---\n", "## Problem 4: Fixing function bugs\n", "\n", "**Objective:** Debug and fix code snippets that contain common function-related errors.\n", "\n", "**Your Task:**\n", "Below are three 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": "e509c52e", "metadata": {}, "source": [ "### Bug 1\n", "\n", "**Expected output:** \n", "```\n", "1\n", "2\n", "3\n", "```\n", "**Current error:** UnboundLocalError" ] }, { "cell_type": "code", "execution_count": null, "id": "4bc42d43", "metadata": {}, "outputs": [], "source": [ "# Bug 1: Fix the code below\n", "\n", "counter = 0\n", "\n", "def increment():\n", " counter = counter + 1\n", "\n", " return counter\n", "\n", "print(increment())\n", "print(increment())\n", "print(increment())" ] }, { "cell_type": "markdown", "id": "060cac8a", "metadata": {}, "source": [ "### Bug 2\n", "\n", "**Expected output:**\n", "```\n", "List 1: ['apple']\n", "List 2: ['banana']\n", "List 3: ['cherry']\n", "```\n", "**Current (wrong) output:**\n", "```\n", "List 1: ['apple', 'banana', 'cherry']\n", "List 2: ['apple', 'banana', 'cherry']\n", "List 3: ['apple', 'banana', 'cherry']\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "85500ff4", "metadata": {}, "outputs": [], "source": [ "# Bug 2: Fix the code below\n", "\n", "def add_to_list(item, my_list=[]):\n", " my_list.append(item)\n", "\n", " return my_list\n", "\n", "list1 = add_to_list('apple')\n", "list2 = add_to_list('banana')\n", "list3 = add_to_list('cherry')\n", "\n", "print('List 1:', list1)\n", "print('List 2:', list2)\n", "print('List 3:', list3)\n" ] }, { "cell_type": "markdown", "id": "92697d30", "metadata": {}, "source": [ "### Bug 3\n", "\n", "**Expected behavior:** Should compare the final price and print appropriate message\n", "\n", "**Current error:** TypeError (comparing None with number)" ] }, { "cell_type": "code", "execution_count": null, "id": "333e1800", "metadata": {}, "outputs": [], "source": [ "# Bug 3: Fix the code below\n", "\n", "def calculate_discount(price, discount_percent):\n", "\n", " discount_amount = price * (discount_percent / 100)\n", " final_price = price - discount_amount\n", "\n", " print(f'Discount: ${discount_amount:.2f}')\n", " print(f'Final price: ${final_price:.2f}')\n", "\n", "result = calculate_discount(100, 20)\n", "\n", "if result < 50:\n", " print('Great deal!')\n", "\n", "else:\n", " print('Consider waiting for a better sale.')\n" ] }, { "cell_type": "markdown", "id": "5791b1a9", "metadata": {}, "source": [ "---\n", "## __Reflection questions__\n", "\n", "After completing the challenges, answer these questions:\n", "\n", "1. When would you use `*args` vs `**kwargs` in a function? Give an example scenario for each.\n", "2. What's the difference between a local and global variable? When should you use the `global` keyword?\n", "3. Why is it important for functions to return values instead of just printing them?\n", "4. What did you learn about default parameter values from the mutable default argument bug?\n", "5. How do you decide what a function should return: a single value, multiple values (tuple), or a data structure?" ] } ], "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 }