Python Forum
Shopping cart program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shopping cart program
#1
#This is a shopping cart program that I am doing for school. I've managed to store the item and price. But can't get to do it the total or remove. I'm new too this and have tried many different methods and it hasten worked. If someone can help please reply
print("Welcome to the Shopping Cart Program!")
cart = []
prices = []
total = []
total_price = []
while True:
    print()
    print ("Please type in one of these")
    print ("1. Add item ")
    print ("2. View cart ")
    print ("3. Remove Item ")
    print ("4 compute total")

    select = int(input(" Type in a number to go on "))
    item = ""
    if select == 1:
        while item != "ok":
            item = input(" What would you like to add?  ")
            price = float(input(" type in the price "))
            prices.append(price)
            
            ok = input ("type in ok when you're done.")
            if item != "ok":
                cart.append(item)
                print(f"'{item}' has been added to your cart.")
                print(f" The price is ${price}")
                break
    if select == 2:
        print("This is what is in your shopping cart")
        for item in cart:
            print(item,price)
            ok = input ("press ok when you're done")
            if item != "ok":
                break
            
    
                    
    if select == 3:
        takeout = input(" Type in what you would like to remove?  ")
        cart.remove(takeout)
        continue
        
    
    if select == 4:
        for price in total_price:
            sum+= price
            print(sum(total_price))
            input ("type in ok when you're done")
            if item != "ok":
                break
            
            
        
    if select == 5:
        print ("comeback soon.")
        break
Yoriz write Jun-26-2022, 06:20 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to ensure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
I can see that you're learning the data types, which is fundamental. Have you covered custom functions yet?

As in...

def myFunction():
    # your code would go here
    return something
If you have, then consider using that technique by defining a function for each operation...

Add Item

View Cart

Remove Item

Compute Total

... so selecting 1, for example, would call the Add Item function, etc.

Note: a Function does not have to 'return' anything (that's optional) rather said Function could simply update a List.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
If you want to take this forward, then it may be best if you posted the assignment notes, so that we don't start down the wrong road.

IMHO you don't need more than 3 user options, which will make for a more user friendly experience. As an example, why make the user have to 'choose' to view the shopping cart (unless that's a part of the assignment notes)? Surely this should be on display by default.

The total cost of the shopping can also be a part of the shopping cart view function, so no need for any 'Compute total'.

This is the approach I would take:

cart = []         #holds the cart items
item_price = []   #holds the price of each item

while True:
    if cart:
        #call the view cart function so that the shopping cart is always on display
        pass  #remove this line when the function has been defined
    else:
        print("\nYour shopping cart is empty.\n")    
    print("Shopping Cart Options\n")
    print ("1. Add items")
    print ("2. Remove Items")
    print ("3. Quit")
 
    option = input("> ")

    if option == '1':
        #call the add items function
        pass #remove this line when the function has been defined

    if option == '2':
        if cart:
            #call the remove items function
            pass #remove this line when the function has been defined
        else:
            print("\nThere are no items in your shopping cart.\n")

    if option == '3':
        if cart:
            #warn the user that there are items in the shopping cart and get positive feedback before quitting
            pass #remove this line when the above in functional 
        else:
            print("\nYour shopping cart is empty.\n")
            check = "yes"
        if check == "yes":
            print("\nApplication exit")
            break
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#4
This whole thing would be significantly easier if you could us a dictionary for your cart. The item name would be the key and the price would be the value. If you've been taught about dictionaries, I would start off with something like this:
cart = {} 
print("Welcome to the Shopping Cart Program!")

while True:
	print()
	print ("Please type in one of these")
	print ("1. Add item ")
	print ("2. View cart ")
	print ("3. Remove Item ")
	print ("4 compute total")
	print ("5 exit program")
 
	select = int(input(" Type in a number to go on "))

	if select == 1:
		item = input(" What would you like to add?  ")
		price = float(input(" type in the price "))
		cart [item] = price
		print(f"'{item}' has been added to your cart.")
		print(f" The price is ${price}")

	if select == 2:
		print("This is what is in your shopping cart")
		for item in cart:
			print(f"  {item} - ${cart [item]}")

	if select == 3:
		takeout = input(" Type in what you would like to remove?  ")
		cart.pop(takeout)

	if select == 4:
		total = 0
		for item in cart:
			total += cart [item]
		print(f" ${total}")

	if select == 5:
		print ("comeback soon.")
		break
Reply
#5
(Jun-26-2022, 11:58 PM)BashBedlam Wrote: This whole thing would be significantly easier if you could us a dictionary for your cart. The item name would be the key and the price would be the value. If you've been taught about dictionaries, I would start off with something like this:
cart = {} 
print("Welcome to the Shopping Cart Program!")

while True:
	print()
	print ("Please type in one of these")
	print ("1. Add item ")
	print ("2. View cart ")
	print ("3. Remove Item ")
	print ("4 compute total")
	print ("5 exit program")
 
	select = int(input(" Type in a number to go on "))

	if select == 1:
		item = input(" What would you like to add?  ")
		price = float(input(" type in the price "))
		cart [item] = price
		print(f"'{item}' has been added to your cart.")
		print(f" The price is ${price}")

	if select == 2:
		print("This is what is in your shopping cart")
		for item in cart:
			print(f"  {item} - ${cart [item]}")

	if select == 3:
		takeout = input(" Type in what you would like to remove?  ")
		cart.pop(takeout)

	if select == 4:
		total = 0
		for item in cart:
			total += cart [item]
		print(f" ${total}")

	if select == 5:
		print ("comeback soon.")
		break
yeah he hasn't the whole class is pretty clueless and stuck
Reply
#6
(Jun-26-2022, 11:29 PM)rob101 Wrote: If you want to take this forward, then it may be best if you posted the assignment notes, so that we don't start down the wrong road.

IMHO you don't need more than 3 user options, which will make for a more user friendly experience. As an example, why make the user have to 'choose' to view the shopping cart (unless that's a part of the assignment notes)? Surely this should be on display by default.

The total cost of the shopping can also be a part of the shopping cart view function, so no need for any 'Compute total'.

This is the approach I would take:

cart = []         #holds the cart items
item_price = []   #holds the price of each item

while True:
    if cart:
        #call the view cart function so that the shopping cart is always on display
        pass  #remove this line when the function has been defined
    else:
        print("\nYour shopping cart is empty.\n")    
    print("Shopping Cart Options\n")
    print ("1. Add items")
    print ("2. Remove Items")
    print ("3. Quit")
 
    option = input("> ")

    if option == '1':
        #call the add items function
        pass #remove this line when the function has been defined

    if option == '2':
        if cart:
            #call the remove items function
            pass #remove this line when the function has been defined
        else:
            print("\nThere are no items in your shopping cart.\n")

    if option == '3':
        if cart:
            #warn the user that there are items in the shopping cart and get positive feedback before quitting
            pass #remove this line when the above in functional 
        else:
            print("\nYour shopping cart is empty.\n")
            check = "yes"
        if check == "yes":
            print("\nApplication exit")
            break
we had to have 5 options and then where we could view the cart and remove an item. it also has to have where you can have more than one item to compute the notes he posted only had for list's which I got stuck many of the other students as well
Reply
#7
(Jun-27-2022, 03:50 AM)Tofuboi03 Wrote: we had to have 5 options

Why then, in your first post, do you only have the 4 options?

Output:
Please type in one of these 1. Add item 2. View cart 3. Remove Item 4 compute total
The No1 thing about ANY project, is to be clear about the objective from the get-go.

Not a worry; we'll put that down to an error on your part.

What have you done over the weekend. Did you make any progress?

So, what you need to do (based on what you've done so far, I know you can do this) is...
  • Clean up your code
    • Correct the Menu: Option 4 needs attention and Option 5 needs to be added.
    • Remember that the 'input()' function returns a string object by default. Your Menu is doing on-the-fly type conversions (str -> int). No need.
    • Your script crashes with no input at the Menu. This needs to be corrected and is an easy fix.
    • Right now you have unused lists defined and will most likely never need them: don't define any objects that you don't use, rather add them as and when there is a use case. You need only two Lists which is easy to manage and keep synchronized.

Right now, I'm not too sure if your heart is in this. If you want to learn, take pride in your work and pay attention to detail. If you make the effort, then others will pay you back in kind, whereas if you don't then you'll be on your own.

You've made a start, but you've also made some sloppy mistakes. Make the corrections and show some interest and we can get this done in no time: I'll help you, if you help yourself.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#8
I see that you're working on a simple shopping cart program in Python. It looks like you're making good progress! However, there are a few issues in your code that need to be addressed to make it work correctly. Let's go through them step by step:

1. Initialize the sum variable to 0 to calculate the total price.

2. You can use a separate list for total_price to keep track of the prices of items in the cart.

3. There's no need for the total and total_price lists; one of them should be sufficient.

4. Use a loop to continuously present the menu options until the user decides to exit.

5. Ensure that you display the total correctly at the end.

Here's an improved version of your code with these issues addressed:

`python
print("Welcome to the Shopping Cart Program!")
cart = []
prices = []

while True:
print()
print("Please select an option:")
print("1. Add item")
print("2. View cart")
print("3. Remove item")
print("4. Compute total")
print("5. Exit")

select = int(input("Type in a number to continue: "))

if select == 1:
item = input("What would you like to add? ")
price = float(input("Type in the price: "))
cart.append(item)
prices.append(price)
print(f"'{item}' has been added to your cart.")
print(f"The price is ${price}")

elif select == 2:
print("This is what is in your shopping cart:")
for i in range(len(cart)):
print(f"{cart[i]} - ${prices[i]}")
input("Press Enter to continue")

elif select == 3:
takeout = input("Type in what you would like to remove: ")
if takeout in cart:
index = cart.index(takeout)
cart.pop(index)
prices.pop(index)
print(f"'{takeout}' has been removed from your cart.")
else:
print(f"'{takeout}' is not in your cart.")

elif select == 4:
if len(cart) == 0:
print("Your cart is empty.")
else:
total_price = sum(prices)
print(f"Total price: ${total_price:.2f}")
input("Press Enter to continue")

elif select == 5:
print("Thank you for shopping with us!")
break

else:
print("Invalid option. Please select a valid option.")
`

This code should work better for your shopping cart program. It allows you to add items, view the cart, remove items, compute the total price, and exit the program. Make sure to copy and paste this code into your Python environment and give it a try.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  project shopping cart pkmnmewtwo 1 3,297 May-03-2020, 10:46 PM
Last Post: pkmnmewtwo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020