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: "))
Now, let's keep track of what we are buying using a list. We need to update our menu so the user can actually see their cart.
Create an empty list called cart at the start of your program.
Update your menu to show three options: 1. Add, 2. View, and 0. Quit.
When the user adds an item:
append that name to your cart list.When the user selects 2, simply print the cart list.
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).
Inside this function, use a while loop and an index variable to print the cart items line-by-line.
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: 3. Remove last item.
When selected, use the pop() method to remove the last item from the cart list.