我该如何解决购物车中的弹出问题

问题描述 投票:0回答:1

我正在开发一个有 5 个选项的购物车,但我很难选择选项 3 来删除(弹出)一个项目。 现在,即使我向列表中添加了更多项目,它也只显示一项。我需要它向我显示所有项目,然后我可以输入一项的编号,然后将其弹出(未删除)。我但在一个无效的数字中,那么它应该循环并再次询问我,但在正确的数字中。

你如何通过代码看出我尝试了一些不同的事情。我输入了 whoöe 代码,因为我在选项 3 之外犯了错误

#shopping cart with the 5 options

items = []
prices = []
ite_pri = items + prices

index = 0
name = None
cost = 0

print('Welcome to the Shopping Cart Program!') 

while name != 'quit':
    
    print()
    print('Please select one of the following: ')
    print('1. Add item \n2. View cart \n3. Remove item \n4. Compute Total \n5. Quit')
    
    option = input ('Please enter an action: ')
    #1. option is to add a item stored in list items and prices, aks how for price and new: how many
    if option == '1':
      name = input('What item would you like to add? ')
      cost = input(f"What is the price of '{name}'? ")
      quantity = input(f"How many '{name}'? ")
      print(f"'{name}' has been added to the cart. ")
      items.append(name)
      prices.append(float(cost) * int(quantity))

# 2. option is to show cart
    elif option == '2':
       print()
       print('The content of the shopping cart are:')
      
       for i in  range(len(items)):
       
            name = items[i]
            cost = prices[i]
   
            print(f'{i+1}.{name} - ${cost}')
# 3. option is to remove (pop) an item
# it only shows one item and befor that it poped the wrong item (when i press 2 it poped the 3. item)
    elif option == '3':
       print()
       print('The content of the shopping cart are:')
      
       for i in  range(len(items)):
       
            name = items[i]
            cost = prices[i]
   
            print(f'{i+1}.{name} - ${cost}')
            
       pop_index = int(input('Which item would you like to remove? ')) 
       if index == pop_index: 
      
               items.pop(int(pop_index))
               break

       print('Item removed.')
                  
       # how can i make it that if user tips in an invalit number that this print comes and he has to but in a new number       
       print('sorry, that is not a valid item number.')
        

# 4. option is to show total
    elif option == '4':
      running_total = 0
      
      for total in prices:
        running_total += float(total)
       
      print(f'The total price of the items in the shopping cart is: {running_total:.2f}')
       


# 5. option is to stop the progress
    elif option == '5':
     print('Thank you. Goodbye.')
     #name != 'quit'
     break
     
python
1个回答
0
投票

为购物商品创建一个类,并将它们存储在 ShoppingItem 对象的购物车数组中,而不是使用 2 个数组。这个重构的代码应该可以解决您的问题

class ShoppingItem:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = float(price)
        self.quantity = int(quantity)

    def total_price(self):
        return self.price * self.quantity

    def __str__(self):
        return f"{self.name} - ${self.price:.2f} x {self.quantity} = ${self.total_price():.2f}"


class ShoppingCart:
    def __init__(self):
        self.items = []

    def add_item(self, name, price, quantity):
        self.items.append(ShoppingItem(name, price, quantity))
        print(f"'{name}' has been added to the cart.")

    def view_cart(self):
        if not self.items:
            print("Your cart is empty.")
        else:
            print("\nThe contents of the shopping cart are:")
            for i, item in enumerate(self.items, 1):
                print(f"{i}. {item}")

    def remove_item(self, index):
        if 0 <= index < len(self.items):
            removed_item = self.items.pop(index)
            print(f"Removed '{removed_item.name}' from the cart.")
        else:
            print("Sorry, that is not a valid item number.")

    def compute_total(self):
        total = sum(item.total_price() for item in self.items)
        print(f"\nThe total price of the items in the shopping cart is: ${total:.2f}")

    def is_empty(self):
        return len(self.items) == 0


def main():
    cart = ShoppingCart()

    print('Welcome to the Shopping Cart Program!')

    while True:
        print()
        print('Please select one of the following:')
        print('1. Add item \n2. View cart \n3. Remove item \n4. Compute Total \n5. Quit')

        option = input('Please enter an action: ')

        # 1. Add item
        if option == '1':
            name = input('What item would you like to add? ')
            price = input(f"What is the price of '{name}'? ")
            quantity = input(f"How many '{name}'? ")
            cart.add_item(name, price, quantity)

        # 2. View cart
        elif option == '2':
            cart.view_cart()

        # 3. Remove item
        elif option == '3':
            if cart.is_empty():
                print("Your cart is empty. Nothing to remove.")
            else:
                cart.view_cart()
                try:
                    pop_index = int(input('Which item would you like to remove? ')) - 1
                    cart.remove_item(pop_index)
                except ValueError:
                    print("Invalid input. Please enter a valid item number.")

        # 4. Compute total
        elif option == '4':
            cart.compute_total()

        # 5. Quit
        elif option == '5':
            print('Thank you. Goodbye.')
            break

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


if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.