简体   繁体   中英

How to update user input result in while loop?

I'm trying to give the user information about the product, but how can I give it to them in case they add another product to the order?

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

so if user orders cola and cake, I want the output to look like this: Your order is 1 cola and 1 cake and total price of it is: sum(final_price)

But every time I execute the code, the older input gets removed and I get the newer input as a result. I want to save it somewhere and show the user everything he/she ordered.

You're defining user_input inside the loop, so it gets overwritten each iteration. You could define an dict

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

before the while loop and update the cart as the user puts items inside, then generate the output with data from the cart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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