From 96a1a40cc434bfeba24c4e5770e90a78e0b3f13d Mon Sep 17 00:00:00 2001 From: REYNOLD TAKURA CHORUMA <153188514+Bhova45@users.noreply.github.com> Date: Thu, 23 Oct 2025 14:41:25 +0200 Subject: [PATCH] lab python functions --- lab-python-functions.ipynb | 547 ++++++++++++++++++++++++++++++++++++- 1 file changed, 545 insertions(+), 2 deletions(-) diff --git a/lab-python-functions.ipynb b/lab-python-functions.ipynb index 44d337b..7d7c75e 100644 --- a/lab-python-functions.ipynb +++ b/lab-python-functions.ipynb @@ -43,11 +43,554 @@ "\n", "\n" ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "2a1255c3", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Initializing Inventory ---\n", + "\n", + "--- Initial Inventory Snapshot ---\n", + "{'book': 5, 'hat': 6, 't-shirt': 3, 'keychain': 4, 'mug': 3}\n" + ] + } + ], + "source": [ + "def initialize_inventory(products):\n", + " \"\"\"\n", + " Initializes the inventory dictionary by prompting the user for the \n", + " starting stock quantity for each product.\n", + "\n", + " Args:\n", + " products (set or list): A collection of product names available.\n", + "\n", + " Returns:\n", + " dict: The inventory dictionary (product_name: stock_quantity).\n", + " \"\"\"\n", + " inventory = {}\n", + " print(\"\\n--- Initializing Inventory ---\")\n", + " \n", + " # Use a loop to iterate through all product names in the 'products' parameter\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " # Prompt the user for input\n", + " quantity_str = input(f\"Enter starting stock for {product}: \")\n", + " quantity = int(quantity_str)\n", + " \n", + " # Check for non-negative input\n", + " if quantity >= 0:\n", + " # Store the product and its stock in the inventory dictionary\n", + " inventory[product] = quantity\n", + " break\n", + " else:\n", + " print(\"Stock quantity cannot be negative. Please enter a non-negative number.\")\n", + " \n", + " except ValueError:\n", + " # Handle cases where the user enters non-numeric input\n", + " print(\"Invalid input. Please enter a whole number for the stock quantity.\")\n", + " \n", + " return inventory\n", + "\n", + "# Example usage:\n", + "# Define the set of products\n", + "available_products = {\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"}\n", + "\n", + "# Call the function to initialize the inventory\n", + "initial_inventory = initialize_inventory(available_products)\n", + "\n", + "# Print the resulting inventory\n", + "print(\"\\n--- Initial Inventory Snapshot ---\")\n", + "print(initial_inventory)\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "a9813a95", + "metadata": {}, + "outputs": [], + "source": [ + "def get_customer_orders():\n", + " \"\"\"\n", + " Prompts the user for product names and quantities to compile a customer order.\n", + "\n", + " Returns:\n", + " dict: The customer orders dictionary (product_name: ordered_quantity).\n", + " \"\"\"\n", + " customer_orders = {}\n", + " print(\"\\n--- Taking Customer Orders ---\")\n", + " print(\"Enter the product name and quantity (e.g., 'mug'). Enter 'done' to finish.\")\n", + "\n", + " # Use a while loop to continuously prompt the user for input\n", + " while True:\n", + " user_input = input(\"Order (Product Quantity / done): \").strip()\n", + " \n", + " # Check for the exit condition\n", + " if user_input.lower() == 'done':\n", + " break\n", + " \n", + " # Split the input into product name and quantity\n", + " parts = user_input.rsplit(' ', 1) # Split only once from the right\n", + " \n", + " # Validate the format of the input\n", + " if len(parts) != 2:\n", + " print(\"Invalid format. Please enter the product name followed by a space and the quantity.\")\n", + " continue\n", + " \n", + " product_name = parts[0].strip()\n", + " quantity_str = parts[1].strip()\n", + " \n", + " try:\n", + " quantity = int(quantity_str)\n", + " \n", + " # Check for valid quantity (positive number)\n", + " if quantity > 0:\n", + " # Add the order to the dictionary. \n", + " # If the product is ordered multiple times, the quantity is summed up.\n", + " customer_orders[product_name] = customer_orders.get(product_name, 0) + quantity\n", + " print(f\"Added {quantity} of {product_name} to the order.\")\n", + " else:\n", + " print(\"Quantity must be a positive whole number.\")\n", + " \n", + " except ValueError:\n", + " print(\"Invalid quantity. Please enter a whole number.\")\n", + " \n", + " return customer_orders\n", + "\n", + "# Example usage (continuing from the previous function's output):\n", + "# orders = get_customer_orders()\n", + "# print(\"\\n--- Customer Orders Placed ---\")\n", + "# print(orders)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "3646aebd", + "metadata": {}, + "outputs": [], + "source": [ + "def update_inventory(customer_orders, inventory):\n", + " \"\"\"\n", + " Updates the inventory by subtracting the quantities specified in the \n", + " customer orders. Prints messages for successful updates and issues.\n", + "\n", + " Args:\n", + " customer_orders (dict): The dictionary of items and quantities ordered.\n", + " inventory (dict): The current inventory dictionary.\n", + "\n", + " Returns:\n", + " dict: The updated inventory dictionary.\n", + " \"\"\"\n", + " print(\"\\n--- Updating Inventory ---\")\n", + " \n", + " # Iterate through each product and its ordered quantity in customer_orders\n", + " for product, ordered_qty in customer_orders.items():\n", + " \n", + " # Check if the ordered product exists in the current inventory\n", + " if product in inventory:\n", + " current_stock = inventory[product]\n", + " \n", + " # Check if there is enough stock to fulfill the order\n", + " if current_stock >= ordered_qty:\n", + " # Fulfill the order and update the stock\n", + " inventory[product] -= ordered_qty\n", + " print(f\"Successfully reduced stock for {product} by {ordered_qty}.\")\n", + " else:\n", + " # Handle insufficient stock\n", + " print(f\"⚠️ Not enough stock for {product}. Ordered: {ordered_qty}, Stock: {current_stock}. Stock reduced to 0.\")\n", + " inventory[product] = 0 # Reduce stock to 0 as much as possible was sold\n", + " else:\n", + " # Handle cases where the product is not in the store's inventory\n", + " print(f\"Product '{product}' is not a recognized item in the store's inventory.\")\n", + " \n", + " return inventory\n", + "\n", + "# Example usage (assuming previous functions were run):\n", + "# Example Inventory: {'Laptop': 5, 'Monitor': 10, 'Keyboard': 8, 'Mouse': 12}\n", + "# Example Orders: {'Laptop': 2, 'Monitor': 15, 'Webcam': 1}\n", + "\n", + "# initial_inventory = {'Laptop': 5, 'Monitor': 10, 'Keyboard': 8, 'Mouse': 12}\n", + "# orders = {'Laptop': 2, 'Monitor': 15, 'Webcam': 1, 'Mouse': 3}\n", + "\n", + "# updated_inventory = update_inventory(orders, initial_inventory)\n", + "\n", + "# print(\"\\n--- Updated Inventory Snapshot ---\")\n", + "# print(updated_inventory)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "138c101f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "--- Order Statistics Results ---\n", + "Total Products Ordered: 17\n", + "Percentage of Unique Available Products Ordered: 80.00%\n" + ] + } + ], + "source": [ + "def calculate_order_statistics(customer_orders, products):\n", + " \"\"\"\n", + " Calculates the total number of products ordered and the percentage of \n", + " unique available products included in the customer's order.\n", + "\n", + " Args:\n", + " customer_orders (dict): The dictionary of items and quantities ordered.\n", + " products (set or list): The full list of available product names.\n", + "\n", + " Returns:\n", + " tuple: A tuple containing (total_products_ordered, percentage_unique_ordered).\n", + " \"\"\"\n", + " \n", + " # 1. Calculate Total Products Ordered\n", + " total_products_ordered = 0\n", + " \n", + " # Sum the quantities (values) from the customer_orders dictionary\n", + " # The .values() method returns a view object that displays a list of all the dictionary's values.\n", + " for quantity in customer_orders.values():\n", + " total_products_ordered += quantity\n", + " \n", + " # 2. Calculate Percentage of Unique Products Ordered\n", + " \n", + " # Get the number of unique products the customer ordered (the keys of the dictionary)\n", + " num_unique_ordered = len(customer_orders)\n", + " \n", + " # Get the total number of unique products available in the store\n", + " total_available_products = len(products)\n", + " \n", + " percentage_unique_ordered = 0.0\n", + " \n", + " # Avoid DivisionByZeroError if the product set is empty\n", + " if total_available_products > 0:\n", + " percentage_unique_ordered = (num_unique_ordered / total_available_products) * 100\n", + " \n", + " # Return both calculated statistics\n", + " return (total_products_ordered, percentage_unique_ordered)\n", + "\n", + "# Example Usage:\n", + "available_products = {\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"}\n", + "customer_orders = {\n", + " \"t-shirt\": 3, \n", + " \"mug\": 3, \n", + " \"hat\": 6,\n", + " \"Non-Stocked Item\": 5 # Items not in 'products' are still counted in the order stats\n", + "}\n", + "\n", + "stats = calculate_order_statistics(customer_orders, available_products)\n", + "\n", + "print(\"\\n--- Order Statistics Results ---\")\n", + "print(f\"Total Products Ordered: {stats[0]}\")\n", + "print(f\"Percentage of Unique Available Products Ordered: {stats[1]:.2f}%\") \n", + "# Expected: (3 unique items ordered that are in 'available_products' / 5 total available) * 100 = 60.00%\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "aabb5a4a", + "metadata": {}, + "outputs": [], + "source": [ + "def print_order_statistics(order_statistics):\n", + " \"\"\"\n", + " Prints the calculated order statistics in a user-friendly format.\n", + "\n", + " Args:\n", + " order_statistics (tuple): A tuple containing \n", + " (total_products_ordered, percentage_unique_ordered).\n", + "\n", + " Returns:\n", + " None: This function performs an action (printing) and does not return a value.\n", + " \"\"\"\n", + " \n", + " # Unpack the tuple for easier access and clarity\n", + " total_products = order_statistics[0]\n", + " percent_unique = order_statistics[1]\n", + " \n", + " print(\"\\n--- Final Order Statistics ---\")\n", + " \n", + " # Print the total number of individual items purchased\n", + " print(f\"Total individual products ordered: {total_products}\")\n", + " \n", + " # Print the percentage, formatted to two decimal places\n", + " print(f\"Percentage of unique available products ordered: {percent_unique:.2f}%\")\n", + " \n", + " print(\"-\" * 30)\n", + "\n", + "# Example usage (assuming the previous function returned this tuple):\n", + "# sample_stats = (35, 60.0) \n", + "# print_order_statistics(sample_stats)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "648abaf3", + "metadata": {}, + "outputs": [], + "source": [ + "def print_updated_inventory(inventory):\n", + " \"\"\"\n", + " Prints the current inventory, showing the remaining stock for each product.\n", + "\n", + " Args:\n", + " inventory (dict): The dictionary containing product names and their current stock quantities.\n", + "\n", + " Returns:\n", + " None: This function performs an action (printing) and does not return a value.\n", + " \"\"\"\n", + " \n", + " print(\"\\n--- Current Inventory Status ---\")\n", + " \n", + " # Check if the inventory is empty\n", + " if not inventory:\n", + " print(\"The inventory is empty.\")\n", + " return\n", + "\n", + " # Iterate through the items in the inventory dictionary\n", + " for product, stock in inventory.items():\n", + " # Determine a status emoji based on stock level for visual feedback\n", + " if stock > 5:\n", + " status = \"🟢\" # High stock\n", + " elif stock > 0:\n", + " status = \"🟡\" # Low stock\n", + " else:\n", + " status = \"🔴\" # Out of stock\n", + "\n", + " # Print the product name and its remaining stock\n", + " print(f\"{status} {product}: {stock} remaining\")\n", + "\n", + " print(\"-\" * 30)\n", + "\n", + "# Example usage (assuming this inventory was returned from update_inventory):\n", + "# updated_inventory_example = {'Laptop': 3, 'Monitor': 0, 'Keyboard': 8, 'Mouse': 9, 'Webcam': 0}\n", + "# print_updated_inventory(updated_inventory_example)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "0c43720e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to the Customer Order Manager!\n", + "\n", + "--- Initializing Inventory ---\n", + "Invalid input. Please enter a whole number.\n", + "\n", + "--- Taking Customer Orders ---\n", + "Enter the product name and quantity (e.g., 'mug 1'). Enter 'done' to finish.\n", + "Invalid format. Please enter the product name followed by a space and the quantity.\n", + "Invalid format. Please enter the product name followed by a space and the quantity.\n", + "\n", + "--- Updating Inventory ---\n", + "\n", + "--- Final Order Statistics ---\n", + "Total individual products ordered: 0\n", + "Percentage of unique available products ordered: 0.00%\n", + "------------------------------\n", + "\n", + "--- Current Inventory Status ---\n", + "🟡 t-shirt: 3 remaining\n", + "🟡 book: 5 remaining\n", + "🟢 hat: 10 remaining\n", + "🟢 keychain: 15 remaining\n", + "🟢 mug: 10 remaining\n", + "------------------------------\n", + "Order management process complete.\n" + ] + } + ], + "source": [ + "# --- FUNCTION DEFINITIONS (As previously developed) ---\n", + "\n", + "def initialize_inventory(products):\n", + " \"\"\"Initializes the inventory dictionary by prompting the user for the \n", + " starting stock quantity for each product.\"\"\"\n", + " inventory = {}\n", + " print(\"\\n--- Initializing Inventory ---\")\n", + " for product in products:\n", + " while True:\n", + " try:\n", + " quantity_str = input(f\"Enter starting stock for {product}: \")\n", + " quantity = int(quantity_str)\n", + " if quantity >= 0:\n", + " inventory[product] = quantity\n", + " break\n", + " else:\n", + " print(\"Stock quantity cannot be negative.\")\n", + " except ValueError:\n", + " print(\"Invalid input. Please enter a whole number.\")\n", + " return inventory\n", + "\n", + "# ----------------------------------------------------------------------\n", + "\n", + "def get_customer_orders():\n", + " \"\"\"Prompts the user for product names and quantities to compile a customer order.\"\"\"\n", + " customer_orders = {}\n", + " print(\"\\n--- Taking Customer Orders ---\")\n", + " print(\"Enter the product name and quantity (e.g., 'mug 1'). Enter 'done' to finish.\")\n", + " while True:\n", + " user_input = input(\"Order (Product Quantity / done): \").strip()\n", + " if user_input.lower() == 'done':\n", + " break\n", + " \n", + " parts = user_input.rsplit(' ', 1)\n", + " if len(parts) != 2:\n", + " print(\"Invalid format. Please enter the product name followed by a space and the quantity.\")\n", + " continue\n", + " \n", + " product_name = parts[0].strip()\n", + " quantity_str = parts[1].strip()\n", + " \n", + " try:\n", + " quantity = int(quantity_str)\n", + " if quantity > 0:\n", + " customer_orders[product_name] = customer_orders.get(product_name, 0) + quantity\n", + " print(f\"Added {quantity} of {product_name} to the order.\")\n", + " else:\n", + " print(\"Quantity must be a positive whole number.\")\n", + " except ValueError:\n", + " print(\"Invalid quantity. Please enter a whole number.\")\n", + " \n", + " return customer_orders\n", + "\n", + "# ----------------------------------------------------------------------\n", + "\n", + "def update_inventory(customer_orders, inventory):\n", + " \"\"\"Updates the inventory by subtracting the quantities specified in the customer orders.\"\"\"\n", + " print(\"\\n--- Updating Inventory ---\")\n", + " for product, ordered_qty in customer_orders.items():\n", + " if product in inventory:\n", + " current_stock = inventory[product]\n", + " if current_stock >= ordered_qty:\n", + " inventory[product] -= ordered_qty\n", + " print(f\"Successfully reduced stock for {product} by {ordered_qty}.\")\n", + " else:\n", + " # Handle insufficient stock\n", + " print(f\"Not enough stock for {product}. Ordered: {ordered_qty}, Stock: {current_stock}. Stock reduced to 0.\")\n", + " inventory[product] = 0\n", + " else:\n", + " print(f\"Product '{product}' is not a recognized item in the store's inventory.\")\n", + " return inventory\n", + "\n", + "# ----------------------------------------------------------------------\n", + "\n", + "def calculate_order_statistics(customer_orders, products):\n", + " \"\"\"Calculates the total number of products ordered and the percentage of \n", + " unique available products included in the customer's order.\"\"\"\n", + " total_products_ordered = sum(customer_orders.values())\n", + " \n", + " num_unique_ordered_available = 0\n", + " # Count how many products ordered are actually in the available 'products' set\n", + " for product in customer_orders.keys():\n", + " if product in products:\n", + " num_unique_ordered_available += 1\n", + " \n", + " total_available_products = len(products)\n", + " \n", + " percentage_unique_ordered = 0.0\n", + " if total_available_products > 0:\n", + " percentage_unique_ordered = (num_unique_ordered_available / total_available_products) * 100\n", + " \n", + " return (total_products_ordered, percentage_unique_ordered)\n", + "\n", + "# ----------------------------------------------------------------------\n", + "\n", + "def print_order_statistics(order_statistics):\n", + " \"\"\"Prints the calculated order statistics in a user-friendly format.\"\"\"\n", + " total_products, percent_unique = order_statistics\n", + " print(\"\\n--- Final Order Statistics ---\")\n", + " print(f\"Total individual products ordered: {total_products}\")\n", + " print(f\"Percentage of unique available products ordered: {percent_unique:.2f}%\")\n", + " print(\"-\" * 30)\n", + "\n", + "# ----------------------------------------------------------------------\n", + "\n", + "def print_updated_inventory(inventory):\n", + " \"\"\"Prints the current inventory, showing the remaining stock for each product.\"\"\"\n", + " print(\"\\n--- Current Inventory Status ---\")\n", + " if not inventory:\n", + " print(\"The inventory is empty.\")\n", + " return\n", + "\n", + " for product, stock in inventory.items():\n", + " if stock > 5:\n", + " status = \"🟢\" # High stock\n", + " elif stock > 0:\n", + " status = \"🟡\" # Low stock\n", + " else:\n", + " status = \"🔴\" # Out of stock\n", + " print(f\"{status} {product}: {stock} remaining\")\n", + " print(\"-\" * 30)\n", + "\n", + "# ----------------------------------------------------------------------\n", + "# --- MAIN PROGRAM EXECUTION SEQUENCE (STEP 7) ---\n", + "\n", + "def run_customer_order_manager():\n", + " \"\"\"\n", + " Calls the functions in the appropriate sequence to execute the program.\n", + " \"\"\"\n", + " \n", + " # 1. Define the set of all products (used for initialization and statistics)\n", + " # NOTE: You must update this list based on your actual assignment requirements.\n", + " available_products = {\"t-shirt\", \"mug\", \"hat\", \"book\", \"keychain\"}\n", + " print(\"Welcome to the Customer Order Manager!\")\n", + "\n", + " # 2. Call initialize_inventory to set up the starting stock\n", + " # The result is stored in the 'inventory' variable\n", + " current_inventory = initialize_inventory(available_products)\n", + "\n", + " # 3. Call get_customer_orders to collect the customer's order\n", + " # The result is stored in the 'orders' variable\n", + " customer_orders = get_customer_orders()\n", + "\n", + " # 4. Call update_inventory to deduct the ordered items from stock\n", + " # This modifies the 'current_inventory' dictionary in place (and returns it)\n", + " current_inventory = update_inventory(customer_orders, current_inventory)\n", + "\n", + " # 5. Call calculate_order_statistics to compute the metrics\n", + " # The result (a tuple) is stored in the 'stats' variable\n", + " order_stats = calculate_order_statistics(customer_orders, available_products)\n", + "\n", + " # 6. Call print_order_statistics to display the calculated metrics\n", + " print_order_statistics(order_stats)\n", + "\n", + " # 7. Call print_updated_inventory to display the remaining stock\n", + " print_updated_inventory(current_inventory)\n", + " \n", + " print(\"Order management process complete.\")\n", + "\n", + "# Execute the main program function\n", + "if __name__ == \"__main__\":\n", + " run_customer_order_manager()\n" + ] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "base", "language": "python", "name": "python3" }, @@ -61,7 +604,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.13.5" } }, "nbformat": 4,