【问题标题】:Shopping List Program购物清单计划
【发布时间】:2021-12-28 14:27:40
【问题描述】:

我正在编写一个程序来模拟某人在杂货店购物。我正在显示所有产品和价格,并提示用户输入他们购买的所有产品,用逗号分隔。我希望程序检查输入是否在产品字典中,并使用循环将其添加到购物车中。在将其添加到购物车之前,程序需要检查输入是否有效,这意味着该项目是否在要购买的产品列表中。当用户选择要购买的商品时,我希望程序询问用户该商品的数量,以及他们想要购买的商品数量。在 samThen 程序将计算所有产品的总和,然后计算税值,占总数的 24%,然后返回一个包含税的小计。这是我目前所拥有的:

def calculatetotal(slist, produce):
    # for each item on the shoping list look up the cost & calculate total price
    item_price = 0
    subtotal = 0
    VAT = 0
    final_total = 0
    basket = {}
    for item in slist:
        item_price = produce.get(item)
        basket[item] = item_price
        subtotal = subtotal + item_price

    basket["Subtotal"] = subtotal

    #calculating VAT
    VAT = subtotal * 0.24
    basket["VAT"] = VAT

    #calculating price with tax
    final_total = subtotal + VAT
    basket["Total"] = final_total

    # print off results
    return basket


def main():
    # set up grocery list with prices
    produce={"Rice":5.00, "Bread":2.00, "Sugar":1.5, "Apple":0.75, "Cereal":3.75, "Gum": 1.00, "Water": 1.75, "Soda": 2.00}
    # process input from the user - get a shopping list
    item = input("Please enter the items that you want to buy: ")
    slist = []
    while(item != 'stop'):
        if not (item in slist):
            slist.append(item)
            item = input("Please enter the items that you want to buy: ")
        
    result = calculatetotal(slist, produce)
    print(result)

main()

我已经得到了大部分,但是我上面提到的一些小改动,我不知道该怎么做。我忘了提到询问物品的数量并检查用户输入是否必须通过循环来完成。非常感谢任何输入。请显示代码的更改。提前谢谢你。

【问题讨论】:

    标签: python arrays python-3.x list dictionary


    【解决方案1】:

    在这种情况下,我会简单地进行一个 while 循环

    while True:
        item = input("Please enter the items that you want to buy: ")
        if item == 'Stop':
            break
        elif item not in produce or item in slist:
            # error message or whatever
        else:
            num = int(input("Enter Quantity"))
            # other operations
    

    【讨论】:

    • 感谢您的意见。我需要为程序添加什么来检查项目的输入是否为数字。如果用户输入一个数字,我希望它只说字母
    • 这通常是我们所说的输入验证,尝试谷歌搜索'输入验证python':)
    • 我想重新表述我原来的问题。我想验证用户输入的项目是否在项目列表中。如果不是,则打印一条消息“该项目不在列表中,请输入另一个输入”
    • 这就是为什么我有条件elif item not in produce的原因,它正在检查你所说的。
    • 如果您觉得解决方案有用请采纳,谢谢!
    猜你喜欢
    • 2020-07-15
    • 2020-08-06
    • 2018-04-07
    • 1970-01-01
    • 2020-03-08
    • 2018-08-03
    • 2020-08-24
    • 2023-04-05
    • 2018-02-02
    相关资源
    最近更新 更多