Menu
CoddyTech

Recap - Shopping Cart Errors

Part of the Logic & Flow section of Coddy's Python journey. Lesson 66 of 78.

challenge icon

Challenge

Medium

Create a program that simulates a shopping cart with error handling. Your task is to:

  1. Create a function called handle_shopping_cart that processes customer orders
  2. The function should accept a list of order strings in the format "item:quantity"
  3. Process each order by:
    • Splitting the input string to get the item and quantity
    • Converting the quantity to an integer
    • Adding the item to a shopping cart dictionary with the quantity as value
    • If an item already exists in the cart, add the new quantity to its existing quantity
  4. Handle these specific errors:
    • If the input format is incorrect (missing colon), print "Invalid format: {order}"
    • If the quantity is not a valid number, print "Invalid quantity: {order}"
    • If the quantity is negative, print "Negative quantity not allowed: {order}"
  5. Return the completed shopping cart dictionary

Check the format and the negative quantity with an if. Only turning the quantity into an integer can raise an error, so except ValueError is where "Invalid quantity: {order}" is printed. Keep the last except Exception as e block as a safety net and print "Unexpected error: {e}" there.

Try it yourself

def handle_shopping_cart(orders):
    # Create an empty dictionary for the shopping cart
    cart = {}

    # Process each order in the list
    for order in orders:
        try:
            # Split the order, check the format and the quantity, then add it to the cart
            pass

        except ValueError:
            # The quantity was not a number
            pass

        except Exception as e:
            # Anything unexpected
            pass

    # Return the completed cart
    return cart

All lessons in Logic & Flow

Practice on your own: Online Python compiler