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
218 changes: 216 additions & 2 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,225 @@
"\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": 27,
"id": "4b3f4a1d",
"metadata": {},
"outputs": [],
"source": [
"# Step 1: Define the function for initializing the inventory with error handling\n",
"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": 28,
"id": "ded52063",
"metadata": {},
"outputs": [],
"source": [
"#2. Modify the `calculate_total_price` function to include error handling.\n",
"#- If the user enters an invalid price (e.g., a negative value or a non-numeric value), display an error message and ask them to re-enter \n",
"# the price for that product.\n",
"#- Use a try-except block to handle the error and continue prompting the user until a valid price is entered.\n",
"def calculate_total_price(customer_orders):\n",
" total = 0 \n",
" for product in customer_orders:\n",
" while True:\n",
" try: \n",
" price = float(input(f\"Enter the price of {product}: \"))\n",
" if price < 0:\n",
" raise ValueError(\"Price cannot be negative\")\n",
" total += price\n",
" break\n",
" except ValueError as e:\n",
" print(f\"Invalid input: {e}. Please enter a non-negative number.\") \n",
" return total "
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "4da9f0eb",
"metadata": {},
"outputs": [],
"source": [
"#3. Modify the `get_customer_orders` function to include error handling.\n",
"#- If the user enters an invalid number of orders (e.g., a negative value or a non-numeric \n",
"# value), display an error message and ask them to re-enter the number of orders.\n",
"#- If the user enters an invalid product name (e.g., a product name that is not in the \n",
"# inventory), or that doesn't have stock available, display an error message and ask \n",
"# them to re-enter the product name. *Hint: you will need to pass inventory as a parameter*\n",
"#- Use a try-except block to handle the error and continue prompting the user until a \n",
"# valid product name is entered.\n",
"\n",
"def get_customer_orders(inventory):\n",
" while True:\n",
" try: \n",
" number_orders = int(input(\"Enter the number of customer orders: \"))\n",
" if number_orders <= 0:\n",
" raise ValueError(\"Number of order have to be greater than 0.\")\n",
" break \n",
" except ValueError as e:\n",
" print(f\"Invalid Value: {e}. Try again, enter a postive integer.\")\n",
"\n",
"\n",
" customer_orders = []\n",
" for i in range(number_orders):\n",
" while True: \n",
" product = input(f\"Enter a product name {i+1}: \").strip()\n",
" if product not in inventory:\n",
" print(f\"Product not available. Choose from: {list(inventory.keys())}\")\n",
" elif inventory[product] <= 0:\n",
" print(f\"{product} is out of stock.\")\n",
" else:\n",
" customer_orders.append(product)\n",
" break\n",
" \n",
" return customer_orders\n"
]
},
{
"cell_type": "markdown",
"id": "004bd5d6",
"metadata": {},
"source": [
"### Llamadas"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "5b4ee123",
"metadata": {},
"outputs": [],
"source": [
"products = ['t-shirt', 'mug', 'hat', 'book', 'keychain']"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "99b50013",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Error: Invalid quantity! Please enter a non-negative value.\n",
"Error: invalid literal for int() with base 10: 'jh'\n"
]
},
{
"data": {
"text/plain": [
"{'t-shirt': 5, 'mug': 4, 'hat': 3, 'book': 2, 'keychain': 1}"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inventory = initialize_inventory(products)\n",
"inventory"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "befe1172",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid Value: invalid literal for int() with base 10: 'i'. Try again, enter a postive integer.\n",
"Invalid Value: invalid literal for int() with base 10: 'df'. Try again, enter a postive integer.\n",
"Invalid Value: invalid literal for int() with base 10: 'hfghfh'. Try again, enter a postive integer.\n",
"Invalid Value: Number of order have to be greater than 0.. Try again, enter a postive integer.\n",
"Product not available. Choose from: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"Product not available. Choose from: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n",
"Product not available. Choose from: ['t-shirt', 'mug', 'hat', 'book', 'keychain']\n"
]
},
{
"data": {
"text/plain": [
"['hat', 'keychain']"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"customer_order = get_customer_orders(inventory)\n",
"customer_order"
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "c61c604a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Invalid input: could not convert string to float: 'gdfg'. Please enter a non-negative number.\n",
"Invalid input: could not convert string to float: 'af'. Please enter a non-negative number.\n",
"Invalid input: Price cannot be negative. Please enter a non-negative number.\n"
]
},
{
"data": {
"text/plain": [
"15.0"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"total_price = calculate_total_price(customer_order)\n",
"total_price"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4cfd9c80",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
Expand All @@ -90,7 +304,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.10.2"
}
},
"nbformat": 4,
Expand Down