Recap - Shopping Cart Errors
Part of the Logic & Flow section of Coddy's Python journey — lesson 66 of 78.
Challenge
MediumCreate a program that simulates a shopping cart with error handling. Your task is to:
- Create a function called
handle_shopping_cartthat processes customer orders - The function should accept a list of order strings in the format "item:quantity"
- 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
- 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}"
- Return the completed shopping cart dictionary
Try it yourself
def handle_shopping_cart(orders):
# Create an empty dictionary for the shopping cart
# Process each order in the list
for order in orders:
try:
# Split the order and add to cart
# Handle potential errors
except ValueError:
# Handle value errors
except Exception as e:
# Handle unexpected errors
# Return the completed cartAll lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter12Basic Error Handling
What is Error Handling?The Try and Except BlockHandling Multiple ExceptionsRecap - Shopping Cart Errors