diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index f4c6ef6..b895c19 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -13,13 +13,13 @@ "id": "bc99b386-7508-47a0-bcdb-d969deaf6c8b", "metadata": {}, "source": [ - "## Exercise: Error Handling for Managing Customer Orders\n", + "## Exercise: Handling errors to manage customer orders\n", "\n", - "The implementation of your code for managing customer orders assumes that the user will always enter a valid input. \n", + "Implementing your code to manage customer orders assumes that the user will always enter valid input. \n", "\n", "For example, we could modify the `initialize_inventory` function to include error handling.\n", - " - If the user enters an invalid quantity (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the quantity for that product.\n", - " - Use a try-except block to handle the error and continue prompting the user until a valid quantity is entered.\n", + " - If the user enters an invalid quantity (for example, a negative value or a non-numeric value), display an error message and ask the user to re-enter the quantity for that product.\n", + " - Use a try-except block to handle the error and continue prompting the user until a valid amount is entered.\n", "\n", "```python\n", "# Step 1: Define the function for initializing the inventory with error handling\n", @@ -57,26 +57,181 @@ " return inventory\n", "```\n", "\n", - "Let's enhance your code by implementing error handling to handle invalid inputs.\n", + "Let's improve your code by implementing error handling to handle invalid input.\n", "\n", "Follow the steps below to complete the exercise:\n", "\n", "2. Modify the `calculate_total_price` function to include error handling.\n", - " - If the user enters an invalid price (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the price for that product.\n", + " - If the user enters an invalid price (for example, a negative value or a non-numeric value), display an error message and ask the user to re-enter the price of that product.\n", " - Use a try-except block to handle the error and continue prompting the user until a valid price is entered.\n", "\n", "3. Modify the `get_customer_orders` function to include error handling.\n", - " - If the user enters an invalid number of orders (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter the number of orders.\n", - " - If the user enters an invalid product name (e.g., a product name that is not in the inventory), or that doesn't have stock available, display an error message and ask them to re-enter the product name. *Hint: you will need to pass inventory as a parameter*\n", - " - Use a try-except block to handle the error and continue prompting the user until a valid product name is entered.\n", + " - If the user enters an invalid order number (for example, a negative value or a non-numeric value), display an error message and ask the user to re-enter the order number.\n", + " - If the user enters an invalid product name (for example, a product name that is not in inventory) or has no stock available, it displays an error message and requests that the user enter the product name again. *Hint: you will need to pass inventory as a parameter*\n", + " - Use a try-except block to handle the error and continue prompting the user until they enter a valid product name.\n", "\n", - "4. Test your code by running the program and deliberately entering invalid quantities and product names. Make sure the error handling mechanism works as expected.\n" + "4. Test your code by running the program and deliberately entering invalid quantities and product names. Make sure the error handling mechanism works as expected." ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "76f35e97", + "metadata": {}, + "outputs": [], + "source": [ + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n", + "def initialize_inventory(products):\n", + " inventory = {}\n", + " for product in products:\n", + " valid_quantity = False\n", + " while not valid_quantity:\n", + " try:\n", + " quantity = int(input(f\"Enter the quantity of {product}s available: \"))\n", + " if quantity < 0:\n", + " raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n", + " valid_quantity = True\n", + " except ValueError as error:\n", + " print(f\"Error: {error}\")\n", + " inventory[product] = quantity\n", + " return inventory" + ] + }, + { + "cell_type": "markdown", + "id": "e4c4b90c", + "metadata": {}, + "source": [ + "2. Modifique la función `calcular_precio_total` para incluir el manejo de errores.\n", + " - Si el usuario ingresa un precio no válido (por ejemplo, un valor negativo o un valor no numérico), muestre un mensaje de error y pídale que vuelva a ingresar el precio de ese producto.\n", + " - Utilice un bloque try-except para manejar el error y continúe preguntando al usuario hasta que se ingrese un precio válido." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "8f75b65e", + "metadata": {}, + "outputs": [], + "source": [ + "def calculate_total_price(productos):\n", + " precio_unitario = []\n", + " for producto in productos:\n", + " valid_price = False\n", + " while not valid_price:\n", + " try:\n", + " precio = float(input(f\"precio de {producto} es:\"))\n", + " if precio < 0:\n", + " raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n", + " valid_price = True\n", + " except ValueError as error:\n", + " print(f\"Error: {error}\")\n", + "\n", + " precio_unitario.append(precio)\n", + " return sum(precio_unitario)\n" + ] + }, + { + "cell_type": "markdown", + "id": "18fb8079", + "metadata": {}, + "source": [ + "3. Modifique la función `get_customer_orders` para incluir el manejo de errores.\n", + " - Si el usuario ingresa un número de pedido no válido (por ejemplo, un valor negativo o un valor no numérico), muestre un mensaje de error y solicite al usuario que vuelva a ingresar el número de pedido.\n", + " - Si el usuario ingresa un nombre de producto no válido (por ejemplo, un nombre de producto que no está en el inventario) o no tiene stock disponible, muestra un mensaje de error y solicita que el usuario ingrese el nombre del producto nuevamente. *Pista: necesitarás pasar el inventario como parámetro*\n", + " - Utilice un bloque try-except para manejar el error y continúe preguntando al usuario hasta que ingrese un nombre de producto válido." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1e22e3b1", + "metadata": {}, + "outputs": [], + "source": [ + "def get_customer_orders(inventory):\n", + " valid_quantity = False\n", + " while not valid_quantity:\n", + " try:\n", + " num_orders = int(input(\"Cantidad de pedidos\"))\n", + " if num_orders < 0:\n", + " raise ValueError(\"Invalid quantity! Please enter a non-negative value.\")\n", + " valid_quantity = True\n", + " except ValueError as error:\n", + " print(f\"Error: {error}\")\n", + " pedidos = []\n", + " for p in range(num_orders):\n", + " valid_products = False\n", + " while not valid_products:\n", + " try:\n", + " producto = input(f\"Ingrese una opcion entre: {list(inventory)}\").lower()\n", + " if producto not in inventory:\n", + " raise ValueError(f\"El producto no valido. Porfavor ingrese una opcion valida\")\n", + " elif inventory[producto] <= 0:\n", + " raise ValueError(f\"El producto {producto} no esta en stock\")\n", + " pedidos.append(producto)\n", + " valid_products = True\n", + " except ValueError as error:\n", + " print(f\"Error: {error}\")\n", + "\n", + " return pedidos" + ] + }, + { + "cell_type": "markdown", + "id": "00003acd", + "metadata": {}, + "source": [ + "4. Pruebe su código ejecutando el programa e ingresando deliberadamente cantidades y nombres de productos no válidos. Asegúrese de que el mecanismo de manejo de errores funcione como se esperaba." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "4b120742", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error: Invalid quantity! Please enter a non-negative value.\n", + "Error: invalid literal for int() with base 10: 'asd'\n", + "{'t-shirt': 1, 'mug': 0, 'hat': 2, 'book': 1, 'keychain': 0}\n", + "Error: Invalid quantity! Please enter a non-negative value.\n", + "Error: invalid literal for int() with base 10: 'asd'\n", + "Error: El producto no valido. Porfavor ingrese una opcion valida\n", + "Error: El producto no valido. Porfavor ingrese una opcion valida\n", + "Error: El producto mug no esta en stock\n", + "Error: El producto keychain no esta en stock\n", + "['hat', 'book']\n", + "20.0\n" + ] + } + ], + "source": [ + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n", + "inventory = initialize_inventory(products)\n", + "print(inventory)\n", + "\n", + "customer_orders = get_customer_orders(inventory)\n", + "print(customer_orders)\n", + "\n", + "print(calculate_total_price(customer_orders))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73030f3a", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "base", "language": "python", "name": "python3" }, @@ -90,7 +245,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.14.6" } }, "nbformat": 4,