A simple checkout flow supports adding, listing and removing products.
What You Need to Understand
A menu-driven shopping cart combines list storage, input handling, conditional branches and loops. For a reliable beginner application, validate commands before changing the cart.
When to Use It
A simple checkout flow supports adding, listing and removing products.
Step-by-Step Python Example
cart = []
commands = [("add", "pen"), ("add", "notebook"), ("remove", "pen")]
for command, product in commands:
if command == "add":
cart.append(product)
elif command == "remove" and product in cart:
cart.remove(product)
print("Cart:", ", ".join(cart))
How the Example Works
The scripted commands illustrate the operations without requiring interactive input. The cart contains only notebook at the end.
Example Output
Cart: notebook
['pear']
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
cart = ["apple", "pear"]
if "apple" in cart:
cart.remove("apple")
print(cart)
Important Behavior and Edge Cases
Never remove without checking membership. A real interactive menu must also handle empty input and an explicit exit command.
Try It Yourself
Extend this example to support a clear command and a list command.
Common Beginner Mistakes
- Never remove without checking membership. A real interactive menu must also handle empty input and an explicit exit command.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- A menu-driven shopping cart combines list storage, input handling, conditional branches and loops.
- The scripted commands illustrate the operations without requiring interactive input.
- Never remove without checking membership.