繁体   English   中英

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

[英]How to update user input result in while loop?

我正在尝试向用户提供有关该产品的信息,但是如果他们向订单中添加了其他产品,我该如何提供给他们?

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(final_price)

但是每次我执行代码时,旧的输入都会被删除,结果我得到了新的输入。 我想将它保存在某个地方并向用户展示他/她订购的所有内容。

您在循环内定义user_input ,因此每次迭代都会被覆盖。 你可以定义一个字典

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

在 while 循环之前,并在用户将商品放入购物车时更新购物车,然后使用购物车中的数据生成输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM