Skip to content
Open

listo #562

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
275 changes: 273 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,282 @@
"\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": "9353452c",
"metadata": {},
"outputs": [],
"source": [
"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": "code",
"execution_count": 3,
"id": "a9908323",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Invalid quantity! Please enter a non-negative value.\n",
"Error: Invalid quantity! Please enter a non-negative value.\n"
]
},
{
"data": {
"text/plain": [
"{'apple': 6, 'banana': 8, 'orange': 1}"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"initialize_inventory(['apple', 'banana', 'orange'])"
]
},
{
"cell_type": "code",
"execution_count": 63,
"id": "7e8ce359",
"metadata": {},
"outputs": [],
"source": [
"productos=[\"camiseta\",\"taza\",\"sombrero\",\"libro\",\"llavero\"]"
]
},
{
"cell_type": "code",
"execution_count": 107,
"id": "5073b201",
"metadata": {},
"outputs": [],
"source": [
"def initialize_inventario(productos):\n",
" inventario = {}\n",
" \n",
" for producto in productos:\n",
" cantidad_valida = False\n",
" while not cantidad_valida:\n",
" try:\n",
" cantidad=int(input(f\"Ingrese la cantidad de {producto} que desea agregar al inventario: \"))\n",
" if cantidad < 0:\n",
" raise ValueError(\"El número de cantidad no puede ser negativo.\")\n",
" elif cantidad == 0:\n",
" raise TypeError(\"El número de cantidad no puede ser cero.\")\n",
" cantidad_valida = True\n",
" except ValueError as e:\n",
" print(f\"Error: {e}. Intente nuevamente.\")\n",
" except TypeError as e:\n",
" print(f\"Error de tipo: {e}. Intente nuevamente.\")\n",
" else:\n",
" cantidad_valida = True\n",
" inventario[producto] = cantidad\n",
" return inventario"
]
},
{
"cell_type": "code",
"execution_count": 92,
"id": "5b435e4e",
"metadata": {},
"outputs": [],
"source": [
"def get_customer_orders():\n",
" customer_orders={}\n",
" pedidovalido = False\n",
" \n",
" while not pedidovalido:\n",
" try:\n",
" pedidos=int(input((\"¿Cuántos productos desea comprar? \")))\n",
" if pedidos < 0:\n",
" raise ValueError(\"El número de pedidos no puede ser negativo.\")\n",
" elif pedidos == 0:\n",
" raise TypeError(\"El número de pedidos no puede ser cero.\")\n",
" pedidovalido = True\n",
" except ValueError as e:\n",
" print(f\"Error: {e}. Intente nuevamente.\")\n",
" except TypeError as e:\n",
" print(f\"Error de tipo: {e}. Intente nuevamente.\")\n",
" else:\n",
" pedidovalido = True\n",
" \n",
" for i in range(pedidos):\n",
" productovalido = False\n",
" while not productovalido:\n",
" try:\n",
" producto = input(f\"Quiero comprar {i+1} entre {productos}: \" )\n",
" if producto not in productos:\n",
" raise KeyError(f\"El producto '{producto}' no está disponible.\")\n",
" productovalido = True\n",
" except KeyError as e:\n",
" print(f\"Error: {e}. Intente nuevamente.\")\n",
" except TypeError as e:\n",
" print(f\"Error de tipo: {e}. Intente nuevamente.\")\n",
" else:\n",
" productovalido = True\n",
" customer_orders[producto] = None\n",
" return customer_orders"
]
},
{
"cell_type": "code",
"execution_count": 69,
"id": "008eca8f",
"metadata": {},
"outputs": [],
"source": [
"def update_inventario(inventario, customer_orders):\n",
" return {x: c - 1 for x, c in inventario.items() if (c - 1 if x in customer_orders else c) > 0}"
]
},
{
"cell_type": "code",
"execution_count": 70,
"id": "f1ae8cac",
"metadata": {},
"outputs": [],
"source": [
"def calculate_order_statistics(customer_orders, productos):\n",
" return (n := len(customer_orders)), (n / len(productos)) * 100"
]
},
{
"cell_type": "code",
"execution_count": 71,
"id": "0558920e",
"metadata": {},
"outputs": [],
"source": [
"def print_order_statistics(order_statistics):\n",
" print(f\"Total de productos pedidos: {order_statistics[0]}\")\n",
" print(f\"Porcentaje de productos únicos pedidos: {order_statistics[1]:.2f}%\")"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "602afe49",
"metadata": {},
"outputs": [],
"source": [
"def print_updated_inventario(nuevo_inventario):\n",
" print(\"Inventario actualizado:\")\n",
" for producto, cantidad in nuevo_inventario.items():\n",
" print(f\"{producto}: {cantidad}\")"
]
},
{
"cell_type": "code",
"execution_count": 84,
"id": "b21f17e3",
"metadata": {},
"outputs": [],
"source": [
"def precio_total(customer_orders):\n",
" precios ={}\n",
" \n",
" for p in customer_orders:\n",
" preciovalidos = False\n",
" while not preciovalidos:\n",
" try:\n",
" precio = float(input(f\"Ingrese el precio de {p}: \"))\n",
" if precio < 0:\n",
" raise ValueError(\"El precio no puede ser negativo.\")\n",
" elif precio == 0:\n",
" raise TypeError(\"El precio no puede ser cero.\")\n",
" else:\n",
" preciovalidos = True\n",
" except ValueError:\n",
" print(\"Error: Ingrese un número válido.\")\n",
" except TypeError:\n",
" print(\"Error: Ingrese un número válido..\")\n",
" else:\n",
" precios[p] = precio\n",
" else:\n",
" preciovalidos = True\n",
" precios[p] = precio\n",
" return precios"
]
},
{
"cell_type": "code",
"execution_count": 73,
"id": "d8b23daf",
"metadata": {},
"outputs": [],
"source": [
"def print_precio_total(precio_total):\n",
" print(f\"Los precios de los productos son: {precio_total}\")\n",
" total = sum(precio_total.values())\n",
" print(f\"El precio total de su compra es: ${total:.2f}\")"
]
},
{
"cell_type": "code",
"execution_count": 109,
"id": "1247976b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Productos disponibles: ['camiseta', 'taza', 'sombrero', 'libro', 'llavero']\n",
"Error: El número de cantidad no puede ser negativo.. Intente nuevamente.\n",
"Error: invalid literal for int() with base 10: '.3'. Intente nuevamente.\n",
"Error: \"El producto 'lo' no está disponible.\". Intente nuevamente.\n",
"Error: \"El producto '5' no está disponible.\". Intente nuevamente.\n",
"Error: \"El producto 'ty' no está disponible.\". Intente nuevamente.\n",
"Total de productos pedidos: 2\n",
"Porcentaje de productos únicos pedidos: 40.00%\n",
"Inventario actualizado:\n",
"camiseta: 5\n",
"taza: 2\n",
"sombrero: 5\n",
"libro: 0\n",
"llavero: 1\n",
"Error: Ingrese un número válido.\n",
"Los precios de los productos son: {'taza': 65.0, 'camiseta': 20.0}\n",
"El precio total de su compra es: $85.00\n"
]
}
],
"source": [
"print(f\"Productos disponibles: {productos}\")\n",
"inventario = initialize_inventario(productos)\n",
"customer_orders = get_customer_orders()\n",
"inventario = update_inventario(inventario, customer_orders)\n",
"estadisticas = calculate_order_statistics(customer_orders, productos)\n",
"print_order_statistics(estadisticas)\n",
"print_updated_inventario(inventario)\n",
"valores=precio_total(customer_orders)\n",
"print_precio_total(valores)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +361,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.1"
}
},
"nbformat": 4,
Expand Down