如何在Python上返回购物车列表中的def菜单

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

我正在练习购物车,其中包括用户输入的商品列表。事情是这样的:

cart_items = []
price_items = []

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

def menu():
        print("1. Add a new item")
        print("2. Display the content of the shopping cart")
        print("3. Remove an item of the shopping cart")
        print("4. Compute total of the items in the shopping cart")
        print("5. Quit")

def display_content():
    for i in range(0, len(cart_items)):
        print(f"{cart_items[i]} - {price_items[i]}")

menu()
option = int(input("Please, enter an action: "))

while option != 5:
    if option == 1:
        new_item = input("What item would you like to add? ")
        price_item = float(input(f"What is the price of the {new_item}? "))
        cart_items.append(new_item)
        price_items.append(price_item)
        print(f"{new_item} has been added to the cart.")
    if option == 2:
        print("The content of the shopping cart are:")
        display_content()
    if option == 3:
        new_item = input("Which item would you like to remove? ")
        temp = []
        for item in cart_items:
            if item[new_item] != new_item:
                temp.append(item)
    if option == 4:
        print('\n\n')
        summation = 0
        for item in cart_items:
            for product in cart_items:
                if product['id'] == item['id']:
                    summation = summation + \
                    (product['price'] * item['quantity'])
                    break
                print(f'The total price of the items in the shopping cart is ${0}'.format(summation))
    elif option >= 5:
        print("Invalid option, please, try again.")
print("Thank you for using the shopping cart program. Good bye!")

因此,对于第一个选项“1”,循环继续要求添加新项目。

我还制作了第一个代码,该代码通常返回到 def 菜单,看起来类似但更简单,并且目前正在按预期工作:

cart_items = []
price_items = []

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

def menu():

        print("1. Add a new item")
        print("2. Display the content of the shopping cart")
        print("3. Quit")

def display_content():
    print(cart_items[0], price_items[0])
for i in range(0, len(cart_items)):
        print(f"{cart_items[i]} - {price_items[i]}")

menu()
option = int(input("Please, enter an action: "))

while option != 3:
    if option == 1:
        new_item = input("What item would you like to add? ")
        price_item = float(input(f"What is the price of the {new_item}? "))
        print(f"{new_item} has been added to the cart.")
        cart_items.append(new_item)
        price_items.append(price_item)
    elif option == 2:
        for i in range(len(cart_items)):
            items = cart_items
            print("The content of the shopping cart are:")
            display_content()
    else:
        print("Invalid option, please, try again.")

    print()
    menu()
    option = int(input("Please, enter an action: "))

print("Thank you for using the shopping cart program. Good bye!")

不确定我是否能够在没有帮助的情况下完成这个程序。我不知道,一开始看起来不错,但最终,在 YT 上举一些例子并不能帮助我完成该程序。彻底的灾难:(

python list function return shopping-cart
2个回答
1
投票

您必须在

menu()
循环内运行
input()
while

在第一个版本中,您没有在

while
循环中使用它,这会产生问题。

但是在第二个版本中,你将它放在

while
循环中并且可以工作。


更简单的版本

while True:

     menu()
     option = int(input("Please, enter an action: "))

     if option == 5:
         break   # exit loop

     # ... check other options ...

编辑:

未测试

# --- functions ---

def menu():
        print("1. Add a new item")
        print("2. Display the content of the shopping cart")
        print("3. Remove an item of the shopping cart")
        print("4. Compute total of the items in the shopping cart")
        print("5. Quit")

def add_item():
    name = input("What item would you like to add? ")
    price = float(input(f"What is the price of the {name}? "))
    cart.append( [name, price] )
    print(f"{name} has been added to the cart.")

def display_content():
    print("The content of the shopping cart are:")

    for name, price in cart:
        print(f"{name} - {price}")

def remove_item():
    selected_name = input("Which item would you like to remove? ")
    temp = []
    for name, price in cart:
        if name != selected_name:
            temp.append( [name, price] )
    cart = temp
    
def total_sum():
    summation = 0

    for name, price in cart:
        summation += price
        
    print(f'The total price of the items in the shopping cart is ${summation}')
    
# --- main ---

cart = []  # keep pairs [name, price]

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

while True:

    menu()
    option = int(input("Please, enter an action: "))

    if option == 5:
        break
    
    elif option == 1:
        add_item()
        
    elif option == 2:
        display_content()
        
    elif option == 3:
        remove_item()
        
    elif option == 4:
        total_sum()
        
    else:
        print("Invalid option, please, try again.")
        
print("Thank you for using the shopping cart program. Good bye!")

0
投票

感谢您发布此帖子,非常有帮助

© www.soinside.com 2019 - 2024. All rights reserved.