From fcf52ff5ed332b3d57d5ffac9f23245333dcece4 Mon Sep 17 00:00:00 2001 From: Beatriz Date: Mon, 23 Feb 2026 21:34:04 +0000 Subject: [PATCH] Lab almost all done --- LAB_python_functions_extra.ipynb | 599 +++++++++++++++++++++++++++++++ 1 file changed, 599 insertions(+) create mode 100644 LAB_python_functions_extra.ipynb diff --git a/LAB_python_functions_extra.ipynb b/LAB_python_functions_extra.ipynb new file mode 100644 index 0000000..faaaa22 --- /dev/null +++ b/LAB_python_functions_extra.ipynb @@ -0,0 +1,599 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e", + "metadata": { + "id": "25d7736c-ba17-4aff-b6bb-66eba20fbf4e" + }, + "source": [ + "# Lab | Functions" + ] + }, + { + "cell_type": "markdown", + "id": "6f8e446f-16b4-4e21-92e7-9d3d1eb551b6", + "metadata": { + "id": "6f8e446f-16b4-4e21-92e7-9d3d1eb551b6" + }, + "source": [ + "Objective: Practice how to define and call functions, pass arguments, return values, and handle scope." + ] + }, + { + "cell_type": "markdown", + "id": "e253e768-aed8-4791-a800-87add1204afa", + "metadata": { + "id": "e253e768-aed8-4791-a800-87add1204afa" + }, + "source": [ + "## Challenge 1: completing functions based on docstring\n", + "\n", + "Complete the functions below according to the docstring, and test them by calling them to make sure they are well implemented." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "df908bed-acc6-4b67-b33a-f3b1c564a49f", + "metadata": { + "id": "df908bed-acc6-4b67-b33a-f3b1c564a49f" + }, + "outputs": [], + "source": [ + " \"\"\"\n", + " Takes a list as an argument and returns a new list with unique elements from the first list.\n", + "\n", + " Parameters:\n", + " lst (list): The input list.\n", + "\n", + " Returns:\n", + " list: A new list with unique elements from the input list.\n", + " \"\"\"\n", + " # your code goes here\n", + "def get_unique_list(lst):\n", + " new_list = []\n", + " new_list = get_unique_list(lst)\n", + " return new_list" + ] + }, + { + "cell_type": "markdown", + "id": "214c2c27-c4fa-46cf-bfbf-26fb25b25882", + "metadata": { + "id": "214c2c27-c4fa-46cf-bfbf-26fb25b25882" + }, + "source": [ + "Example:\n", + "\n", + "*Input [1,2,3,3,3,3,4,5] -> type: list*\n", + "\n", + "*Expected Output [1,2,3,4,5] -> type: list*" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "7d5c8e34-a116-4428-ab9d-e0e15e338fff", + "metadata": { + "id": "7d5c8e34-a116-4428-ab9d-e0e15e338fff", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "04a06afb-6e51-42ac-f7a5-6362a63c8143" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "There are 2 upper case letters and 8 lower case letters in Hello World.\n" + ] + } + ], + "source": [ + "\"\"\"\n", + " Returns the number of uppercase and lowercase letters in the given string.\n", + "\n", + " Parameters:\n", + " string (str): The string to count uppercase and lowercase letters in.\n", + "\n", + " Returns:\n", + " A tuple containing the count of uppercase and lowercase letters in the string.\n", + " \"\"\"\n", + "def count_case(string):\n", + " uppercase_count = 0\n", + " lowercase_count = 0\n", + "\n", + " for char in string:\n", + " if char.isupper():\n", + " uppercase_count += 1\n", + " elif char.islower():\n", + " lowercase_count += 1\n", + "\n", + " return (f\"There are {uppercase_count} upper case letters and {lowercase_count} lower case letters in {example_string}.\")\n", + "\n", + "example_string = \"Hello World\"\n", + "print(count_case(example_string))" + ] + }, + { + "cell_type": "markdown", + "id": "2c902b2e-369c-4a40-a166-ca5bc554cab3", + "metadata": { + "id": "2c902b2e-369c-4a40-a166-ca5bc554cab3" + }, + "source": [ + "Example:\n", + "\n", + "*Input: \"Hello World\"*\n", + "\n", + "*Expected Output: Uppercase count: 2, Lowercase count: 8*" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "c15b91d4-cfd6-423b-9f36-76012b8792b8", + "metadata": { + "id": "c15b91d4-cfd6-423b-9f36-76012b8792b8", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "a2c1f1de-3f17-4a4f-9cc6-cca7beb201f4" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "There are 2 words in the sentence.\n" + ] + } + ], + "source": [ + "import string\n", + "\n", + "\"\"\"\n", + " Removes all punctuation marks (commas, periods, exclamation marks, question marks) from a sentence.\n", + "\n", + " Parameters:\n", + " sentence (str): A string representing a sentence.\n", + "\n", + " Returns:\n", + " str: The sentence without any punctuation marks.\n", + " \"\"\"\n", + "\n", + "\"\"\"\n", + " Counts the number of words in a given sentence. To do this properly, first it removes punctuation from the sentence.\n", + " Note: A word is defined as a sequence of characters separated by spaces. We can assume that there will be no leading or trailing spaces in the input sentence.\n", + "\n", + " Parameters:\n", + " sentence (str): A string representing a sentence.\n", + "\n", + " Returns:\n", + " int: The number of words in the sentence.\n", + " \"\"\"\n", + "\n", + "def word_count(sentence):\n", + " # Remove punctuation from the sentence\n", + " cleaned_sentence = ''.join(char for char in sentence if char not in string.punctuation)\n", + " # Split the cleaned sentence into words\n", + " words = cleaned_sentence.split()\n", + " # Return the count of words\n", + " return len(words)\n", + "\n", + "# Example usage\n", + "example_sentence = \"Hello, world!\"\n", + "print(f\"There are {word_count(example_sentence)} words in the sentence.\")" + ] + }, + { + "cell_type": "markdown", + "id": "52814e4d-7631-4c80-80b6-2b206f7e7419", + "metadata": { + "id": "52814e4d-7631-4c80-80b6-2b206f7e7419" + }, + "source": [ + "*For example, calling*\n", + "```python\n", + "word_count(\"Note : this is an example !!! Good day : )\")\n", + "```\n", + "\n", + "*would give you as expected output: 7*" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "id": "f7cfd32a-f559-47ff-81c1-2576bd4fe3bf", + "metadata": { + "id": "f7cfd32a-f559-47ff-81c1-2576bd4fe3bf", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "4b005cb7-37ca-43b7-8936-d5099c49015e" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "There are 7 words in the sentence.\n" + ] + } + ], + "source": [ + "def word_count(sentence):\n", + " cleaned_sentence = ''.join(char for char in sentence if char not in string.punctuation)\n", + " words = cleaned_sentence.split()\n", + " return len(words)\n", + "\n", + "example_sentence = \"Note : this is an example !!! Good day : )\"\n", + "print(f\"There are {word_count(example_sentence)} words in the sentence.\")" + ] + }, + { + "cell_type": "markdown", + "id": "fb01ccba-2ecc-4eea-b9a9-2bf9d29e8804", + "metadata": { + "id": "fb01ccba-2ecc-4eea-b9a9-2bf9d29e8804" + }, + "source": [ + "## Challenge 2: Build a Calculator\n", + "\n", + "In this exercise, you will build a calculator using Python functions. The calculator will be able to perform basic arithmetic operations like addition, subtraction, multiplication, and division.\n", + "\n", + "Instructions\n", + "- Define four functions for addition, subtraction, multiplication, and division.\n", + "- Each function should take two arguments, perform the respective arithmetic operation, and return the result.\n", + "- Define another function called \"calculate\" that takes three arguments: two operands and an operator.\n", + "- The \"calculate\" function should use a conditional statement to determine which arithmetic function to call based on the operator argument.\n", + "- The \"calculate\" function should then call the appropriate arithmetic function and return the result.\n", + "- Test your \"calculate\" function by calling it with different input parameters.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "id": "57f9afc7-8626-443c-9c3e-eb78ef503193", + "metadata": { + "id": "57f9afc7-8626-443c-9c3e-eb78ef503193", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "615b4c21-1c33-4d38-f570-e3efa35495ec" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "9.2\n" + ] + } + ], + "source": [ + "import math\n", + "\n", + "def addition(num1, num2):\n", + " result = num1 + num2\n", + " return result\n", + "\n", + "def subtraction(num1, num2):\n", + " result = num1 - num2\n", + " return result\n", + "\n", + "def multiplication(num1, num2):\n", + " result = num1 * num2\n", + " return result\n", + "\n", + "def division(num1, num2):\n", + " if num2 == 0:\n", + " return \"Error: Division by zero is not allowed.\"\n", + " result = num1 / num2\n", + " return result\n", + "\n", + "def calculate(num1, num2, operator):\n", + " if operator == '+':\n", + " return addition(num1, num2)\n", + " elif operator == '-':\n", + " return subtraction(num1, num2)\n", + " elif operator == '*':\n", + " return multiplication(num1, num2)\n", + " elif operator == '/':\n", + " return division(num1, num2)\n", + " else:\n", + " return \"Invalid operator\"\n", + "\n", + "#example to test it\n", + "num1 = 46\n", + "num2 = 5\n", + "operator = '/'\n", + "result = calculate(num1, num2, operator)\n", + "print(result)" + ] + }, + { + "cell_type": "markdown", + "id": "d1784c63-208c-4553-9686-acac6c0a9dda", + "metadata": { + "id": "d1784c63-208c-4553-9686-acac6c0a9dda" + }, + "source": [ + "### Bonus: args and kwargs\n", + "\n", + "Update the previous exercise so it allows for adding, subtracting, and multiplying more than 2 numbers.\n", + "\n", + "The calculator will be able to perform basic arithmetic operations like addition, subtraction, multiplication, and division on multiple numbers.\n", + "\n", + "*Hint: use args or kwargs. Recommended external resource: [Args and Kwargs in Python](https://www.geeksforgeeks.org/args-kwargs-python/)*" + ] + }, + { + "cell_type": "code", + "execution_count": 76, + "id": "ff3e816c-13ab-447d-a6f2-bb47a8fad2e2", + "metadata": { + "id": "ff3e816c-13ab-447d-a6f2-bb47a8fad2e2", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "d8991912-5bd0-4b3b-fcce-7c27a869a5b1" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "24\n" + ] + } + ], + "source": [ + "def addition(*args):\n", + " result = sum(args)\n", + " return result\n", + "\n", + "def subtraction(*args):\n", + " result = args[0] - sum(args[1:])\n", + " return result\n", + "\n", + "def multiplication(*args):\n", + " result = 1\n", + " for num in args:\n", + " result *= num\n", + " return result\n", + "\n", + "def division(*args):\n", + " result = args[0]\n", + " for num in args[1:]:\n", + " if num == 0:\n", + " return \"Error: Division by zero is not allowed.\"\n", + " result /= num\n", + " return result\n", + "\n", + "def calculate(*args):\n", + " if len(args) < 3:\n", + " return \"At least two numbers and an operator are required.\"\n", + "\n", + " # Separate the numbers and the operator\n", + " numbers = args[:-1]\n", + " operator = args[-1]\n", + "\n", + " # Determine the operation based on the operator provided\n", + " if operator == '+':\n", + " return addition(*numbers)\n", + " elif operator == '-':\n", + " return subtraction(*numbers)\n", + " elif operator == '*':\n", + " return multiplication(*numbers)\n", + " elif operator == '/':\n", + " return division(*numbers)\n", + " else:\n", + " return \"Invalid operator\"\n", + "\n", + "# Example usage\n", + "num1 = 1\n", + "num2 = 2\n", + "num3 = 3\n", + "num4 = 4\n", + "operator = '*'\n", + "print(calculate(num1, num2, num3, num4, operator))" + ] + }, + { + "cell_type": "markdown", + "id": "af2de734-2a0e-4458-9cb8-57284b7108ae", + "metadata": { + "id": "af2de734-2a0e-4458-9cb8-57284b7108ae" + }, + "source": [ + "## Challenge 3: importing functions from a Python file" + ] + }, + { + "cell_type": "markdown", + "id": "56780ce8-6610-4fb5-a4ef-22cd46af83d2", + "metadata": { + "id": "56780ce8-6610-4fb5-a4ef-22cd46af83d2" + }, + "source": [ + "Moving the functions created in Challenge 1 to a Python file.\n", + "\n", + "- In the same directory as your Jupyter Notebook, create a new Python file called `functions.py`.\n", + "- Copy and paste the functions you created earlier in the Jupyter Notebook into the functions.py file. Rename the functions to `get_unique_list_f, count_case_f, remove_punctuation_f, word_count_f`. Add the _f suffix to each function name to ensure that you're calling the functions from your file.\n", + "- Save the `functions.py` file and switch back to the Jupyter Notebook.\n", + "- In a new cell, import the functions from functions.py\n", + "- Call each function with some sample input to test that they're working properly.\n", + "\n", + "There are several ways to import functions from a Python module such as functions.py to a Jupyter Notebook:\n", + "\n", + "1. Importing specific functions: If you only need to use a few functions from the module, you can import them individually using the from keyword. This way, you can call the functions directly using their names, without having to use the module name. For example:\n", + "\n", + "```python\n", + "from function_file import function_name\n", + "\n", + "function_name(arguments)```\n", + "\n", + "2. Importing the entire module: You can import the entire module using the import keyword followed by the name of the module. Then, you can call the functions using the module_name.function_name() syntax. Example:\n", + "\n", + "```python\n", + "import function_file\n", + "\n", + "function_file.function_name()\n", + "```\n", + "\n", + "3. Renaming functions during import: You can also rename functions during import using the as keyword. This is useful if you want to use a shorter or more descriptive name for the function in your code. For example:\n", + "\n", + "```python\n", + "from function_file import function_name as f\n", + "\n", + "f.function_name(arguments)\n", + "```\n", + "\n", + "Regardless of which method you choose, make sure that the functions.py file is in the same directory as your Jupyter Notebook, or else specify the path to the file in the import statement or by using `sys.path`.\n", + "\n", + "You can find examples on how to import Python files into jupyter notebook here:\n", + "- https://medium.com/cold-brew-code/a-quick-guide-to-understanding-pythons-import-statement-505eea2d601f\n", + "- https://www.geeksforgeeks.org/absolute-and-relative-imports-in-python/\n", + "- https://www.pythonforthelab.com/blog/complete-guide-to-imports-in-python-absolute-relative-and-more/\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "id": "14f222c5-e7bb-4626-b45c-bd735001f768", + "metadata": { + "id": "14f222c5-e7bb-4626-b45c-bd735001f768" + }, + "source": [ + "To ensure that any changes made to the Python file are reflected in the Jupyter Notebook upon import, we need to use an IPython extension that allows for automatic reloading of modules. Without this extension, changes made to the file won't be reloaded or refreshed in the notebook upon import.\n", + "\n", + "For that, we will include the following code:\n", + "```python\n", + "%load_ext autoreload\n", + "%autoreload 2\n", + "```\n", + "\n", + "You can read more about this here: https://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5832ecfe-c652-418d-8fbc-bac4b1166b40", + "metadata": { + "id": "5832ecfe-c652-418d-8fbc-bac4b1166b40" + }, + "outputs": [], + "source": [ + "# IPython extension to reload modules before executing user code.\n", + "%load_ext autoreload\n", + "%autoreload 2\n", + "\n", + "# your code goes here" + ] + }, + { + "cell_type": "markdown", + "id": "06d0eb13-8dcb-4783-8f74-8f71beb2d0b4", + "metadata": { + "id": "06d0eb13-8dcb-4783-8f74-8f71beb2d0b4" + }, + "source": [ + "## Bonus: recursive functions\n", + "\n", + "The Fibonacci sequence is a mathematical sequence that appears in various fields, including nature, finance, and computer science. It starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers. The sequence goes like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on.\n", + "\n", + "Write a Python function that uses recursion to compute the Fibonacci sequence up to a given number n.\n", + "\n", + "To accomplish this, create a function that calculates the Fibonacci number for a given input. For example, the 10th Fibonacci number is 55.\n", + "Then create another function that generates a list of Fibonacci numbers from 0 to n.\n", + "Test your function by calling it with different input parameters." + ] + }, + { + "cell_type": "markdown", + "id": "b1686493-48bb-47f1-b3c9-75994816b277", + "metadata": { + "id": "b1686493-48bb-47f1-b3c9-75994816b277" + }, + "source": [ + "Example:\n", + "\n", + "*Expected output for n = 14:*\n", + "\n", + "*Fibonacci sequence: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]*" + ] + }, + { + "cell_type": "code", + "execution_count": 89, + "id": "a1d55cea-96c3-4853-8220-17c0904a8816", + "metadata": { + "id": "a1d55cea-96c3-4853-8220-17c0904a8816", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "be577239-ff56-47d0-e8b5-2fac60c926c3" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Fibonacci sequence up to the 14th number is: 377\n" + ] + } + ], + "source": [ + "def fibonacci(n):\n", + " if n <= 0:\n", + " return 0\n", + " elif n == 1:\n", + " return 1\n", + " else:\n", + " return fibonacci(n - 1) + fibonacci(n - 2)\n", + "\n", + "n = 14\n", + "print(f\"Fibonacci sequence up to the {n}th number is: {fibonacci(n)}\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.9.13" + }, + "colab": { + "provenance": [], + "include_colab_link": true + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file