Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 84 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,93 @@
"\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"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "c59ec9d6",
"metadata": {},
"outputs": [],
"source": [
"# 2. Modify the `calculate_total_price` function to include error handling.\n",
"\n",
"def calculate_price(customer_orders):\n",
" price_order = {}\n",
"\n",
" for product in customer_orders:\n",
" valid_price = False\n",
"\n",
" while not valid_price:\n",
" try:\n",
" price = float(input(f\"Introduzca el precio de {product}: \"))\n",
"\n",
" if price < 0:\n",
" raise ValueError(\"El precio no puede ser negativo.\")\n",
"\n",
" price_order[product] = price\n",
" valid_price = True\n",
"\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Introduzca un precio válido.\")\n",
"\n",
" return sum(price_order.values())\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "5fb5664d",
"metadata": {},
"outputs": [],
"source": [
"# 3. Modify the `get_customer_orders` function to include error handling.\n",
"\n",
"def get_customer_orders(inventory):\n",
" customer_orders = set()\n",
"\n",
" # PEDIR NÚMERO DE PRODUCTOS \n",
" valid_number = False\n",
" while not valid_number:\n",
" try:\n",
" num_orders = int(input(\"¿Cuántos productos desea pedir?: \"))\n",
"\n",
" if num_orders <= 0:\n",
" raise ValueError(\"El número debe ser mayor que 0.\")\n",
"\n",
" valid_number = True\n",
"\n",
" except ValueError as error:\n",
" print(f\"Error: {error}. Introduzca un número válido.\")\n",
"\n",
" # INTRODUCIR CADA PRODUCTO \n",
" for i in range(num_orders):\n",
" valid_product = False\n",
"\n",
" while not valid_product:\n",
" product = input(f\"Producto {i+1}: \").lower()\n",
"\n",
" # Validar que el producto existe\n",
" if product not in inventory:\n",
" print(\"Error: producto no existe en el inventario.\")\n",
" continue\n",
"\n",
" # Validar que hay stock disponible\n",
" if inventory[product] <= 0:\n",
" print(\"Error: no queda stock de ese producto.\")\n",
" continue\n",
"\n",
" # Si todo OK, lo añadimos\n",
" customer_orders.add(product)\n",
" valid_product = True\n",
"\n",
" return customer_orders\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +172,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.7"
}
},
"nbformat": 4,
Expand Down