From a69a174b10995bf5f3abc4d44c709dac22c9b030 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Maria=20Monteiro?= Date: Fri, 16 Jan 2026 12:32:21 +0000 Subject: [PATCH] Add files via upload --- lab-python-error-handling.ipynb | 292 +++++++++++++++++++++++++++++++- 1 file changed, 290 insertions(+), 2 deletions(-) diff --git a/lab-python-error-handling.ipynb b/lab-python-error-handling.ipynb index f4c6ef6..b04a6ab 100644 --- a/lab-python-error-handling.ipynb +++ b/lab-python-error-handling.ipynb @@ -72,11 +72,299 @@ "\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": null, + "id": "20f5f944", + "metadata": {}, + "outputs": [], + "source": [ + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n", + "inventory = {}\n", + "costumer_orders = set()\n", + "\n", + "def initialize_inv(products):\n", + " \"\"\" It will prompt a inventory initializer, where you will have to enter the initial quantities for the items in {products}\"\"\"\n", + " inventory = {product:int(input(f\"Insert the quantity of {product}\")) for product in products}\n", + " return print(inventory)\n", + "\n", + "\n", + "initialize_inv(products)\n", + "\n", + "def get_costumer_orders():\n", + " order_number = input(\"Insert the number of orders to process:\")\n", + " ordered ={costumer_orders.add(input(\"Enter the name of the product you want to order\")) for i in range(int(order_number))}\n", + " return ordered\n", + "\n", + "get_costumer_orders()\n", + "\n", + "def update_inventory(costumer_orders, inventory):\n", + " \"\"\"It will update the inventory based on the costumer orders\"\"\"\n", + " inventory = {name: inventory[name] - 1 for name in costumer_orders if inventory[name] > 0}\n", + " \n", + " return print(inventory)\n", + " \n", + "\n", + "price = {}\n", + "\n", + "def order_price(product, price):\n", + " \"\"\"It will return the price of the ordered product\"\"\"\n", + " price = {product: int(input(f\"How much does {product} cost?\")) for product in costumer_orders}\n", + " total_price = sum(price.values())\n", + " print(f\"The total price of the order is: {total_price}\")\n", + " return total_price\n", + "\n", + "order_price(products, price)\n", + "\n", + "def calculate_order_statistics(costumer_orders, products):\n", + " print(\"Order Statistics:\")\n", + " total_orders = len(costumer_orders)\n", + " print(f\"Total Products Ordered: {total_orders}\")\n", + " unique_products = len(products)\n", + " total_unique = (total_orders / unique_products) * 100\n", + " print(f\"Percentage of Products Ordered: {int(total_unique)}%\")\n", + "\n", + " return total_orders, total_unique\n", + "\n", + "calculate_order_statistics(costumer_orders, products)\n", + "\n", + "def print_order_statistics(order_statistics):\n", + " total_orders, total_unique = order_statistics\n", + " print(\"Order Statistics:\")\n", + " print(f\"Total Products Ordered: {total_orders}\")\n", + " print(f\"Percentage of Products Ordered: {int(total_unique)}%\")\n", + " return total_orders, total_unique\n", + "\n", + "\n", + "def print_updated_inventory(inventory):\n", + " \"\"\"It will print the updated inventory report\"\"\"\n", + " print(\"Updated Inventory:\")\n", + " [print(f\"Inventory of {item} : {inventory[item]}\") for item in inventory]\n", + " return inventory\n", + "\n", + " \n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e5962560", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"\"Calculate Total price\"\"\"\n", + "\n", + "price = {}\n", + "\n", + "def order_price(product, price):\n", + " \"\"\"It will return the price of the ordered product\"\"\"\n", + " price = {product: int(input(f\"How much does {product} cost?\")) for product in costumer_orders}\n", + " total_price = sum(price.values())\n", + " print(f\"The total price of the order is: {total_price}\")\n", + " return total_price\n", + "\n", + "order_price(products, price)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "9c793b74", + "metadata": {}, + "outputs": [], + "source": [ + "def calculate_total_price(items):\n", + " item_prices = {}\n", + " \n", + " for item in items:\n", + " while True:\n", + " try:\n", + " cost = int(input(f\"Quanto custa o item '{item}'? \"))\n", + " if cost < 0:\n", + " print(\"Erro: O preço não pode ser negativo. Tente novamente.\")\n", + " item_prices[item] = cost\n", + " except ValueError:\n", + " print(\"Erro: Entrada inválida. Por favor, digite apenas números inteiros.\")\n", + "\n", + " total_price = sum(item_prices.values())\n", + " print(f\"Total: {total_price}\")\n", + " \n", + " return total_price" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3377ebb5", + "metadata": {}, + "outputs": [], + "source": [ + "\"\"\"Get_costumer_orders\"\"\"\n", + "def get_customer_orders(inventory):\n", + " while True:\n", + " try:\n", + " order_number = int(input(\"Insira o número de produtos a encomendar: \"))\n", + " if order_number < 0:\n", + " print(\"Erro: O número de pedidos não pode ser negativo.\")\n", + " except ValueError:\n", + " print(\"Erro: Entrada inválida. Por favor, insira um número inteiro.\")\n", + " customer_orders = []\n", + " for i in range(order_number):\n", + " while True:\n", + " try:\n", + " product_name = input(f\"Produto {i+1}: \").strip()\n", + " if product_name not in inventory:\n", + " raise KeyError(f\"O produto '{product_name}' não existe no nosso inventário.\")\n", + " if inventory[product_name] <= 0:\n", + " raise ValueError(f\"O produto '{product_name}' está esgotado.\")\n", + " customer_orders.append(product_name)\n", + " except (KeyError, ValueError) as e:\n", + " print(f\"Erro: {e} Tente novamente.\")\n", + "\n", + " return customer_orders\n", + "\n", + "get_customer_orders(inventory)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "79f49742", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Inicialização do Inventário ---\n", + "\n", + "--- Definição de Preços ---\n", + "Erro: O preço deve ser positivo.\n", + "Erro: O preço deve ser positivo.\n", + "Erro: Insira um número inteiro.\n", + "\n", + "Preço Total do Pedido: 70\n", + "\n", + "--- Estatísticas do Pedido ---\n", + "Total de itens pedidos: 2\n", + "Percentagem do catálogo requisitada: 40%\n", + "\n", + "--- Inventário Atualizado ---\n", + "Stock de t-shirt: 30\n", + "Stock de mug: 29\n", + "Stock de hat: 29\n", + "Stock de book: 30\n", + "Stock de keychain: 30\n" + ] + } + ], + "source": [ + "\"\"\"código atualizado\"\"\"\n", + "\n", + "products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n", + "\n", + "def initialize_inv(products):\n", + " \"\"\"Inicializa o inventário com as quantidades fornecidas pelo utilizador.\"\"\"\n", + " print(\"\\n--- Inicialização do Inventário ---\")\n", + " # Retornamos o dicionário para ser guardado numa variável\n", + " return {product: int(input(f\"Quantidade inicial de {product}: \")) for product in products}\n", + "\n", + "def get_customer_orders(inventory):\n", + " \"\"\"Recolhe os pedidos validando stock e existência.\"\"\"\n", + " while True:\n", + " try:\n", + " order_number = int(input(\"\\nQuantos produtos deseja encomendar? \"))\n", + " if order_number >= 0:\n", + " break # Importante: Sair do loop se o valor for válido\n", + " print(\"Erro: O número não pode ser negativo.\")\n", + " except ValueError:\n", + " print(\"Erro: Insira um número inteiro válido.\")\n", + "\n", + " customer_orders = []\n", + " for i in range(order_number):\n", + " while True:\n", + " try:\n", + " product_name = input(f\"Produto {i+1}: \").strip().lower()\n", + " if product_name not in inventory:\n", + " raise KeyError(f\"O produto '{product_name}' não existe.\")\n", + " if inventory[product_name] <= 0:\n", + " raise ValueError(f\"O produto '{product_name}' está esgotado.\")\n", + " \n", + " customer_orders.append(product_name)\n", + " # Opcional: reduzir stock imediatamente aqui ou na função própria\n", + " break\n", + " except (KeyError, ValueError) as e:\n", + " print(f\"Erro: {e} Tente novamente.\")\n", + " return customer_orders\n", + "\n", + "def update_inventory(customer_orders, inventory):\n", + " \"\"\"Atualiza o inventário subtraindo os itens pedidos.\"\"\"\n", + " for item in customer_orders:\n", + " if inventory[item] > 0:\n", + " inventory[item] -= 1\n", + " return inventory\n", + "\n", + "def calculate_total_price(items_ordered):\n", + " \"\"\"Calcula o preço total com base nos itens realmente pedidos.\"\"\"\n", + " print(\"\\n--- Definição de Preços ---\")\n", + " item_prices = {}\n", + " # Usamos set() para não perguntar o preço do mesmo item duas vezes\n", + " for item in set(items_ordered):\n", + " while True:\n", + " try:\n", + " cost = int(input(f\"Preço unitário de '{item}': \"))\n", + " if cost >= 0:\n", + " item_prices[item] = cost\n", + " break\n", + " print(\"Erro: O preço deve ser positivo.\")\n", + " except ValueError:\n", + " print(\"Erro: Insira um número inteiro.\")\n", + " \n", + " total = sum(item_prices[item] for item in items_ordered)\n", + " print(f\"\\nPreço Total do Pedido: {total}\")\n", + " return total\n", + "\n", + "def print_order_statistics(customer_orders, products):\n", + " \"\"\"Calcula e exibe estatísticas do pedido.\"\"\"\n", + " print(\"\\n--- Estatísticas do Pedido ---\")\n", + " total_ordered = len(customer_orders)\n", + " unique_ordered = len(set(customer_orders))\n", + " total_catalog = len(products)\n", + " \n", + " percentage = (unique_ordered / total_catalog) * 100\n", + " print(f\"Total de itens pedidos: {total_ordered}\")\n", + " print(f\"Percentagem do catálogo requisitada: {int(percentage)}%\")\n", + "\n", + "def print_updated_inventory(inventory):\n", + " \"\"\"Exibe o estado final do stock.\"\"\"\n", + " print(\"\\n--- Inventário Atualizado ---\")\n", + " for item, qty in inventory.items():\n", + " print(f\"Stock de {item}: {qty}\")\n", + "\n", + "\n", + "current_inventory = initialize_inv(products)\n", + "orders = get_customer_orders(current_inventory)\n", + "current_inventory = update_inventory(orders, current_inventory)\n", + "total_pago = calculate_total_price(orders)\n", + "print_order_statistics(orders, products)\n", + "print_updated_inventory(current_inventory)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e8137279", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "base", "language": "python", "name": "python3" }, @@ -90,7 +378,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.9" } }, "nbformat": 4,