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
268 changes: 266 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,275 @@
"\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": "markdown",
"id": "b383f78e",
"metadata": {},
"source": [
"### ANSWER"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "9ab94e79",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"=== CUSTOMER ORDER MANAGEMENT SYSTEM ===\n",
"\n",
"Step 1: Initialize Inventory\n",
"\n",
"Initial inventory: {'t-shirt': 5, 'mug': 10, 'hat': 12, 'book': 8, 'keychain': 12}\n",
"\n",
"==================================================\n",
"Step 2: Get Customer Orders\n",
"'mug' added to order. Total: 1 product(s).\n",
"'hat' added to order. Total: 2 product(s).\n",
"Error: 'spoone' is not in the inventory. Available products: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"'t-shirt' added to order. Total: 3 product(s).\n",
"'book' added to order. Total: 4 product(s).\n",
"Order confirmed with 4 product(s).\n",
"\n",
"Customer orders: {'t-shirt', 'hat', 'book', 'mug'}\n",
"\n",
"==================================================\n",
"Step 3: Calculate Total Price\n",
"\n",
"Total price of the order: $47.00\n",
"\n",
"==================================================\n",
"Step 4: Update Inventory\n",
"\n",
"--- Updated Inventory ---\n",
"t-shirt: 4\n",
"mug: 9\n",
"hat: 11\n",
"book: 7\n",
"keychain: 12\n",
"\n",
"==================================================\n",
"Step 5: Order Statistics\n",
"\n",
"--- Order Statistics ---\n",
"Percentage of unique products ordered: 80.0%\n",
"Total products ordered: 4\n",
"\n",
"==================================================\n",
"Program completed successfully!\n"
]
}
],
"source": [
"# ============================================================================\n",
"# FONCTION 1 : Initialize Inventory (fournie dans l'énoncé)\n",
"# ============================================================================\n",
"\n",
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" while True: # Repeat until valid input\n",
" try:\n",
" qty = int(input(f\"Quantity for {product}: \"))\n",
" if qty < 0:\n",
" # Explicitly raising an error for negative values\n",
" raise ValueError(\"Negative numbers are not allowed.\")\n",
" inventory[product] = qty\n",
" break # Exit the while loop if input is valid\n",
" except ValueError:\n",
" # Catching both text input and raised negative value error\n",
" print(\"Invalid input. Please enter a positive whole number.\")\n",
" return inventory\n",
"\n",
"\n",
"# ============================================================================\n",
"# FONCTION 2 : Calculate Total Price (à corriger selon l'énoncé)\n",
"# ============================================================================\n",
"\n",
"def calculate_total_price(customer_orders):\n",
" total = 0\n",
" for product in customer_orders:\n",
" while True:\n",
" try:\n",
" # float() is used to allow prices like 9.99\n",
" price = float(input(f\"Price for {product}: \"))\n",
" total += price\n",
" break\n",
" except ValueError:\n",
" print(\"Error: Please enter a valid price (numeric).\")\n",
" return total\n",
"\n",
"\n",
"# ============================================================================\n",
"# FONCTION 3 : Get Customer Orders (à corriger selon l'énoncé)\n",
"# ============================================================================\n",
"\n",
"def get_customer_orders(inventory):\n",
" \"\"\"\n",
" Récupère les commandes clients avec validation complète :\n",
" - Nombre de commandes valide (entier positif)\n",
" - Produits existants dans l'inventaire\n",
" - Produits avec stock disponibles\n",
" - Possibilité d'annuler avec 'escape'\n",
" - Possibilité de confirmer avec 'Enter' vide après avoir entré au moins 1 produit\n",
" \"\"\"\n",
" customer_orders = set()\n",
" \n",
" # Validation du nombre de commandes\n",
" valid_num = False\n",
" while not valid_num:\n",
" try:\n",
" num_orders_input = input(\"Enter the number of customer orders: \").strip().lower()\n",
" if num_orders_input == 'escape':\n",
" print(\"Order cancelled.\")\n",
" return set()\n",
" num_orders = int(num_orders_input)\n",
" if num_orders <= 0:\n",
" raise ValueError(\"Please enter a positive number.\")\n",
" valid_num = True\n",
" except ValueError as error:\n",
" print(f\"Invalid input! {error}\")\n",
" \n",
" # Récupération des produits commandés\n",
" for i in range(num_orders):\n",
" valid_product = False\n",
" while not valid_product:\n",
" prompt = f\"Enter the name of product {i+1} (or press 'Enter' to finish, or type 'escape' to cancel): \"\n",
" product = input(prompt).strip().lower()\n",
" \n",
" # ✅ Permettre de sortir avec 'escape'\n",
" if product == 'escape':\n",
" print(\"Order cancelled.\")\n",
" return set()\n",
" \n",
" # ✅ Permettre de confirmer avec Entrée vide SI au moins 1 produit a été saisi\n",
" if not product:\n",
" if len(customer_orders) > 0:\n",
" print(f\"Order confirmed with {len(customer_orders)} product(s).\")\n",
" return customer_orders\n",
" else:\n",
" print(\"Error: Product name cannot be empty. Please enter at least one product.\")\n",
" continue\n",
" \n",
" # Vérifier que le produit existe dans l'inventaire\n",
" if product not in inventory:\n",
" print(f\"Error: '{product}' is not in the inventory. Available products: {list(inventory.keys())}\")\n",
" continue\n",
" \n",
" # Vérifier que le produit a du stock disponible\n",
" if inventory[product] <= 0:\n",
" print(f\"Error: '{product}' is out of stock. Please choose another product.\")\n",
" continue\n",
" \n",
" # ✅ Si tout est valide, ajouter au set et passer au suivant\n",
" customer_orders.add(product)\n",
" print(f\"'{product}' added to order. Total: {len(customer_orders)} product(s).\")\n",
" valid_product = True\n",
" \n",
" # ✅ Si on arrive ici, c'est qu'on a fini tous les produits demandés\n",
" print(f\"Order completed with {len(customer_orders)} product(s).\")\n",
" return customer_orders\n",
"\n",
"\n",
"# ============================================================================\n",
"# FONCTIONS SUPPLÉMENTAIRES (pour un programme complet)\n",
"# ============================================================================\n",
"\n",
"def update_inventory(customer_orders, inventory):\n",
" \"\"\"\n",
" Met à jour l'inventaire en soustrayant les produits commandés.\n",
" \"\"\"\n",
" for product in customer_orders:\n",
" if product in inventory:\n",
" inventory[product] -= 1\n",
" return inventory\n",
"\n",
"\n",
"def calculate_order_statistics(customer_orders, products):\n",
" \"\"\"\n",
" Calcule les statistiques de commande.\n",
" \"\"\"\n",
" total_products_ordered = len(customer_orders)\n",
" unique_products_ordered = len(set(customer_orders))\n",
" if len(products) > 0:\n",
" percentage_unique = round((unique_products_ordered / len(products)) * 100, 2)\n",
" else:\n",
" percentage_unique = 0\n",
" return {\n",
" 'percentage_unique': percentage_unique, \n",
" 'total_products_ordered': total_products_ordered\n",
" }\n",
"\n",
"\n",
"def print_order_statistics(order_statistics):\n",
" \"\"\"\n",
" Affiche les statistiques de commande.\n",
" \"\"\"\n",
" print(\"\\n--- Order Statistics ---\")\n",
" print(f\"Percentage of unique products ordered: {order_statistics['percentage_unique']}%\")\n",
" print(f\"Total products ordered: {order_statistics['total_products_ordered']}\")\n",
"\n",
"\n",
"def print_updated_inventory(inventory):\n",
" \"\"\"\n",
" Affiche l'inventaire mis à jour.\n",
" \"\"\"\n",
" print(\"\\n--- Updated Inventory ---\")\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")\n",
"\n",
"\n",
"# ============================================================================\n",
"# PROGRAMME PRINCIPAL - TEST COMPLET\n",
"# ============================================================================\n",
"\n",
"if __name__ == \"__main__\":\n",
" # Définir les produits disponibles\n",
" products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
" \n",
" print(\"=== CUSTOMER ORDER MANAGEMENT SYSTEM ===\\n\")\n",
" \n",
" # 1. Initialiser l'inventaire\n",
" print(\"Step 1: Initialize Inventory\")\n",
" inventory = initialize_inventory(products)\n",
" print(f\"\\nInitial inventory: {inventory}\")\n",
" \n",
" # 2. Récupérer les commandes clients (avec validation)\n",
" print(\"\\n\" + \"=\"*50)\n",
" print(\"Step 2: Get Customer Orders\")\n",
" customer_orders = get_customer_orders(inventory)\n",
" print(f\"\\nCustomer orders: {customer_orders}\")\n",
" \n",
" # 3. Calculer le prix total (avec validation)\n",
" print(\"\\n\" + \"=\"*50)\n",
" print(\"Step 3: Calculate Total Price\")\n",
" total_price = calculate_total_price(customer_orders)\n",
" print(f\"\\nTotal price of the order: ${total_price:.2f}\")\n",
" \n",
" # 4. Mettre à jour l'inventaire\n",
" print(\"\\n\" + \"=\"*50)\n",
" print(\"Step 4: Update Inventory\")\n",
" inventory = update_inventory(customer_orders, inventory)\n",
" print_updated_inventory(inventory)\n",
" \n",
" # 5. Calculer et afficher les statistiques\n",
" print(\"\\n\" + \"=\"*50)\n",
" print(\"Step 5: Order Statistics\")\n",
" order_stats = calculate_order_statistics(customer_orders, products)\n",
" print_order_statistics(order_stats)\n",
" \n",
" print(\"\\n\" + \"=\"*50)\n",
" print(\"Program completed successfully!\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "base",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +354,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.9"
}
},
"nbformat": 4,
Expand Down