This project is a cumulative test of your journey so far. You will need to apply:
while loops.In this project, you will build a shopping program. Unlike previous exercises, this requires maintaining a persistent state (your money and your cart) throughout a loop until the user decides to quit.
First, we need to handle the money. Your program should ensure that the user cannot buy something they cannot afford.
Write a program that first asks for a Starting Budget.
Then, create a loop that prints the current budget and asks for a command:
1: Add item0: QuitIf the user selects 1, ask for the Price of the item.
float() to convert the input so you can perform math correctly:budget=float(input("Budget: "))
⚠️ Keep working in the SAME file! Do not create a new file for this phase. You are expanding on the code you just wrote.
Now, let's keep track of what we are buying using a list. We need to update our existing loop and menu so the user can actually see their cart.
Create an empty list called cart at the very start of your program.
Inside your loop, you should still print the current budget, but replace your old menu to show three options instead of two: 1. Add, 2. View, and 0. Quit.
When the user adds an item:
append that name to your cart list (and still subtract the price like in Phase 1).When the user selects 2, simply print the cart list.
⚠️ Once again, stay in your same project file! We are modifying your existing code.
In Part 4, we learned that global code can become messy. Let's move our display logic into a function and format the list so it doesn't look like a raw Python list with brackets.
Step 1 (Formatting): When adding an item, use an f-string to store the name and price together in the list as one string, for example: "Apple ($2.5)".
Step 2 (The Function): Create a function print_status(budget, cart) at the top of your file.
Inside this function, print the current budget, then use a while loop and an index variable to print the cart items line-by-line.
Replace the budget and view print statements in your main loop with a call to this new function.
defprint_status(budget, cart):f"Current Budget: {budget}")iflen(cart) ==0:"Cart is empty")else:# Use a while loop to print each item nicely
for loops yet, use a counter:
i =0whilei <len(cart):f"- {cart[i]}") i +=1
What if the user accidentally adds the wrong item? Add one last menu option to your existing loop: 3. Remove last item.
When selected, use the pop() method to remove the last item from the cart list.