如何在while循环中更新用户输入结果?

2024-05-29 09:49:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着给用户提供关于产品的信息,但是如果他们在订单中添加了其他产品,我怎么给他们呢?你知道吗

import datetime

db = [
    {
        'product': 'cola',
        'price': {
            'USD': '2',
            'GEL': '6'
        },
        'amount': 20,
        'validity': '17/12/2019'
    },
    {
        'product': 'cake',
        'price': {
            'USD': '3',
            'GEL': '9'
        },
        'amount': 15,
        'validity': '17/12/2019'
    },
    {
        'product': 'tea',
        'price': {
            'USD': '1',
            'GEL': '3'
        },
        'amount': 14,
        'validity': '17/12/2019'
    },
]

amount_of_product = {}
validity_of_product = {}
prices_of_product = {}


for i in db:
    amount_of_product.update({i["product"]: i["amount"]})
    validity_of_product.update({i["product"]: i["validity"]})
    prices_of_product.update({i["product"]: i["price"]})

adLoop = True
final_price = []

while adLoop:
    user_input = input("Please enter a product name: ")
    if user_input in amount_of_product.keys() and validity_of_product.keys():
        print(f"Currently, we have {amount_of_product[user_input]} amount of {user_input} left, "
              f"which are valid through {validity_of_product[user_input]}")

    user_input_two = int(input("Please enter the amount: "))
    user_input_three = input("In which currency would you like to pay in?(GEL or USD: ").upper()
    price = prices_of_product[user_input][user_input_three]
    total = user_input_two * int(price)
    if user_input_three == "GEL":
        final_price.append(total)
        print(f"Your order is: {user_input_two} {user_input} and total price for it is: {total}₾")
    elif user_input_three == "USD":
        final_price.append(total * 3)
        print(f"Your order is: {user_input_two} {user_input} and total price for it is: {total}$")

    stop_or_order = input("Would you like to add anything else?: ")
    if stop_or_order == "yes":
        adLoop = True
    elif stop_or_order == "no":
        adLoop = False

因此,如果用户订购可乐和蛋糕,我希望输出如下所示: 您的订单是1杯可乐和1块蛋糕,总价是:sum(最终价格)

但是每次我执行代码时,旧的输入都会被删除,结果会得到新的输入。我想把它保存在某个地方,并向用户显示他/她点的所有东西。你知道吗


Tags: orofinputorderproductamountpricetotal
1条回答
网友
1楼 · 发布于 2024-05-29 09:49:15

在循环中定义用户输入,因此每次迭代都会覆盖它。你可以定义一个dict

user_shopping_cart = {
  'cola':0,
  'cake':0,
  'tea':0
}

在while循环之前,当用户将项目放入购物车时更新购物车, 然后使用购物车中的数据生成输出。你知道吗

相关问题 更多 >

    热门问题