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
312 changes: 308 additions & 4 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,324 @@
"\n"
]
},
{
"cell_type": "markdown",
"id": "116fa5ad",
"metadata": {},
"source": [
"# 1. Define a function named `initialize_inventory` that takes `products` as a parameter. \n",
"def initialize_inventory(products):\n",
" #Inside the function, implement the code for initializing the inventory dictionary using a loop and user input.\n",
" inventory = {product: int(input(f\"Please input the amount of the product {product}\")) for product in products}\n",
" #return dictionary\n",
" return inventory "
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 1,
"id": "cc2c441d-9dcf-4817-b097-cf6cbe440846",
"metadata": {},
"outputs": [],
"source": [
"# your code goes here"
"def initialize_inventory(products):\n",
" inventory = {}\n",
" for product in products:\n",
" while True:\n",
" try:\n",
" quantity = int(input(f\"Please input the amount of the product {product}: \"))\n",
" if quantity < 0:\n",
" raise ValueError(\"Quantity cannot be negative!\")\n",
" inventory[product] = quantity\n",
" break # exit the while loop if input is valid\n",
" except ValueError as e:\n",
" print(f\"Invalid input: {e}. Please enter a positive whole number.\")\n",
" return inventory"
]
},
{
"cell_type": "markdown",
"id": "901cf8fd",
"metadata": {},
"source": [
"# 2.Define a function named `get_customer_orders` that takes no parameters. \n",
"def get_customer_orders():\n",
"#Inside the function, implement the code for prompting the user to enter the product names using a loop. The function should return the `customer_orders` set.\n",
" customer_orders = set()\n",
" \n",
" while True:\n",
" order = input(\"please enter the product you would like to order:\") \n",
" #add to customer_order\n",
" customer_orders.add(order)\n",
" #ask for more\n",
" next_order = input(\"Would you like to order something else? Please enter 'yes' or 'no':\").strip().lower() \n",
" if next_order == 'no':\n",
" break\n",
" #return set\n",
" return customer_orders"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "26276df2",
"metadata": {},
"outputs": [],
"source": [
"def get_customer_orders(products, inventory): # add inventory as parameter\n",
" customer_orders = set()\n",
" order_counts = {} # track how many times each product is ordered\n",
" \n",
" while True:\n",
" try:\n",
" order = input(\"Please enter the product you would like to order: \").strip().lower()\n",
" \n",
" if order not in products:\n",
" raise ValueError(f\"'{order}' is not in our inventory!\")\n",
" \n",
" # check if enough stock available\n",
" times_ordered = order_counts.get(order, 0)\n",
" if times_ordered >= inventory[order]:\n",
" raise ValueError(f\"Sorry! Only {inventory[order]} '{order}' available in stock!\")\n",
" \n",
" customer_orders.add(order)\n",
" order_counts[order] = times_ordered + 1\n",
" print(f\"'{order}' added to your order! ✅ (Stock remaining: {inventory[order] - order_counts[order]})\")\n",
" \n",
" except ValueError as e:\n",
" print(f\"Invalid input: {e}. Please try again.\")\n",
" continue\n",
" \n",
" next_order = input(\"Would you like to order something else? Please enter 'yes' or 'no': \").strip().lower()\n",
" if next_order == 'no':\n",
" break\n",
" elif next_order != 'yes':\n",
" print(\"Please enter 'yes' or 'no'!\")\n",
" \n",
" return customer_orders"
]
},
{
"cell_type": "markdown",
"id": "5bcd88ab",
"metadata": {},
"source": [
"# 3.Define a function named `update_inventory` that takes `customer_orders` and `inventory` as parameters. \n",
"def update_inventory(customer_orders, inventory):\n",
"#Inside the function, implement the code for updating the inventory dictionary based on the customer orders.\n",
" #return {product: (quantity -1 if product in customer_orders else quantity) for product, quantity in inventory.items()}\n",
" inventory = {product: (quantity -1 if product in customer_orders else quantity) for product, quantity in inventory.items()}\n",
" return inventory"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "c611e08b",
"metadata": {},
"outputs": [],
"source": [
"def update_inventory(customer_orders, inventory):\n",
" try:\n",
" # check if inputs are valid\n",
" if not isinstance(customer_orders, set):\n",
" raise TypeError(\"customer_orders must be a set!\")\n",
" if not isinstance(inventory, dict):\n",
" raise TypeError(\"inventory must be a dictionary!\")\n",
" if len(customer_orders) == 0:\n",
" raise ValueError(\"customer_orders is empty — no orders to process!\")\n",
" \n",
" # check if ordered products are in inventory\n",
" for product in customer_orders:\n",
" if product not in inventory:\n",
" raise ValueError(f\"'{product}' is not in the inventory!\")\n",
" if inventory[product] <= 0:\n",
" raise ValueError(f\"'{product}' is out of stock!\")\n",
" \n",
" # update inventory\n",
" inventory = {product: (quantity - 1 if product in customer_orders else quantity) \n",
" for product, quantity in inventory.items()}\n",
" return inventory\n",
" \n",
" except TypeError as e:\n",
" print(f\"Type error: {e}\")\n",
" except ValueError as e:\n",
" print(f\"Value error: {e}\")"
]
},
{
"cell_type": "markdown",
"id": "0b3f0bfe",
"metadata": {},
"source": [
"# 4.Define a function named `calculate_order_statistics` that takes `customer_orders` and `products` as parameters. \n",
"def calculate_order_statistics(customer_orders, products):\n",
"#Inside the function, implement the code for calculating the order statistics (total products ordered, and percentage of unique products ordered). \n",
" total_products_ordered = len(customer_orders)\n",
" percentage_unique_products = (total_products_ordered / len(products)) *100\n",
"#The function should return these values.\n",
" return total_products_ordered, percentage_unique_products"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "fe5c1539",
"metadata": {},
"outputs": [],
"source": [
"#Define a function named `calculate_order_statistics` that takes `customer_orders` and `products` as parameters. \n",
"def calculate_order_statistics(customer_orders, products):\n",
"# Inside the function, implement the code for calculating the order statistics (total products ordered, and percentage of unique products ordered). \n",
" total_products_ordered = len(customer_orders)\n",
" percentage_unique_products = (total_products_ordered / len(products)) *100\n",
"# The function should return these values.\n",
" return total_products_ordered, percentage_unique_products"
]
},
{
"cell_type": "markdown",
"id": "00cf3a19",
"metadata": {},
"source": [
"# 5.Define a function named `print_order_statistics` that takes `order_statistics` as a parameter. \n",
"def print_order_statistics(order_statistics):\n",
" #define order_statistics\n",
" total_products_ordered, percentage_unique_products = order_statistics\n",
"\n",
" #Inside the function, implement the code for printing the order statistics.\n",
" print(f\"Total products ordered: {total_products_ordered}\\n\"\n",
" f\"Percentage of unique products ordered: {percentage_unique_products: .2f}%\")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "56464ddd",
"metadata": {},
"outputs": [],
"source": [
"def calculate_order_statistics(customer_orders, products):\n",
" try:\n",
" # check if inputs are valid\n",
" if not isinstance(customer_orders, set):\n",
" raise TypeError(\"customer_orders must be a set!\")\n",
" if not isinstance(products, list):\n",
" raise TypeError(\"products must be a list!\")\n",
" if len(products) == 0:\n",
" raise ValueError(\"Products list is empty — cannot calculate statistics!\")\n",
" if len(customer_orders) == 0:\n",
" raise ValueError(\"No orders found — cannot calculate statistics!\")\n",
" if len(customer_orders) > len(products):\n",
" raise ValueError(\"Number of orders cannot exceed number of products!\")\n",
"\n",
" # calculate statistics\n",
" total_products_ordered = len(customer_orders)\n",
" percentage_unique_products = (total_products_ordered / len(products)) * 100\n",
" \n",
" return total_products_ordered, percentage_unique_products\n",
"\n",
" except TypeError as e:\n",
" print(f\"Type error: {e}\")\n",
" except ValueError as e:\n",
" print(f\"Value error: {e}\")\n",
" except ZeroDivisionError:\n",
" print(\"Error: Cannot divide by zero — products list is empty!\")"
]
},
{
"cell_type": "markdown",
"id": "50bddea5",
"metadata": {},
"source": [
"# 6.Define a function named `print_updated_inventory` that takes `inventory` as a parameter. \n",
"def print_updated_inventory(inventory):\n",
"#Inside the function, implement the code for printing the updated inventory.\n",
" for product, quantity in inventory.items():\n",
" print(f\"{product}: {quantity}\")"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "6449bb91",
"metadata": {},
"outputs": [],
"source": [
"def print_updated_inventory(inventory):\n",
" try:\n",
" if not isinstance(inventory, dict):\n",
" raise TypeError(\"Inventory must be a dictionary!\")\n",
" if len(inventory) == 0:\n",
" raise ValueError(\"Inventory is empty — nothing to print!\")\n",
" \n",
" print(\"\\nUpdated Inventory:\")\n",
" for product, quantity in inventory.items():\n",
" if not isinstance(quantity, int):\n",
" raise TypeError(f\"Quantity for '{product}' must be a whole number!\")\n",
" if quantity < 0:\n",
" raise ValueError(f\"Quantity for '{product}' cannot be negative!\")\n",
" print(f\"{product}: {quantity}\")\n",
" \n",
" except TypeError as e:\n",
" print(f\"Type error: {e}\")\n",
" except ValueError as e:\n",
" print(f\"Value error: {e}\")"
]
},
{
"cell_type": "markdown",
"id": "e55a0dea",
"metadata": {},
"source": [
"call the functions"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "a2686eed",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"'book' added to your order! ✅ (Stock remaining: 0)\n",
"Please enter 'yes' or 'no'!\n",
"Invalid input: Sorry! Only 1 'book' available in stock!. Please try again.\n",
"'mug' added to your order! ✅ (Stock remaining: 1)\n",
"'mug' added to your order! ✅ (Stock remaining: 0)\n",
"Invalid input: Sorry! Only 2 'mug' available in stock!. Please try again.\n",
"'t-shirt' added to your order! ✅ (Stock remaining: 0)\n",
"\n",
"Order Statistics:\n",
"(3, 60.0)\n",
"\n",
"Updated Inventory:\n",
"{'t-shirt': 0, 'mug': 1, 'hat': 3, 'book': 0, 'keychain': 2}\n"
]
}
],
"source": [
"#Call the functions in the appropriate sequence to execute the program and manage customer orders.\n",
"# define products\n",
"products = [\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"]\n",
"inventory = initialize_inventory(products)\n",
"customer_orders = get_customer_orders(products, inventory)\n",
"updated_inventory = update_inventory(customer_orders, inventory)\n",
"order_statistics = calculate_order_statistics(customer_orders, products)\n",
"#print\n",
"print(\"\\nOrder Statistics:\")\n",
"print(order_statistics)\n",
"print(\"\\nUpdated Inventory:\")\n",
"print(updated_inventory)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -66,7 +370,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.14.2"
}
},
"nbformat": 4,
Expand Down