【问题标题】:How to update user input result in while loop?如何在while循环中更新用户输入结果?
【发布时间】:2019-12-19 09:37:12
【问题描述】:

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

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)

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

【问题讨论】:

  • 然后将其保存到某种数据库中?可以是内存字典,其中键是用户名/用户 ID,值是顺序。
  • 你一直在写输入,所以它当然只打印最后一个条目。使用列表之类的数据结构来按顺序存储每个项目
  • 是的,明白了。感谢您的帮助。
  • 不是已发布问题的一部分,但您不会在进入循环之前或最后在计算价格时询问货币吗?我怀疑你需要用美元支付可乐和用凝胶支付茶的功能
  • 其实是的,这只是一个测试代码。一切都将在最后一个修复

标签: python python-3.x loops while-loop


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2013-11-16
    • 2020-02-15
    • 2015-12-31
    相关资源
    最近更新 更多