Home > Net >  List of products price comparison (with while loop)
List of products price comparison (with while loop)

Time:03-20

I've been writing the code, which have to check if the product from input is in list and if it is true - add it to total cost

But there is a problem which i stuck on really hard When i make first input - all code is working properly, but when i try to input another products - they just take the price of first inputed one, so it often looks like this:

#first input
Spirulini
#result = Spirulini costs 31 usd
#         Total cost is 31 usd
#second input
Sause
#result = Sause costs 31 usd
#         Total cost is 62 usd

I think that is happening somehow because of while cycle, so would be glad if someone could help me with that issue. Also i would love to hear any feedback about how i can simplify this code, as soon as i am beginner in Python

The whole code:

productlist = ['Shaurma','Spirulini','Sause','Cabbage']
pricelist = [56,31,4,9]
totalcost = 0

inpt = input()
indx = productlist.index(inpt)
price = pricelist[indx]
endWord = 'stop'

while inpt.lower() != endWord.lower():

  if inpt in productlist:
    totalcost  = price
    print("\n{} costs {:d} usd".format(inpt, price))
    print (f'Total cost is {totalcost}')
    inpt = input()

  elif inpt not in productlist:
    print("Product is not found, try again")
    inpt = input()

CodePudding user response:

You need to update the indx and price at each iteration of the while loop. The product to look up changes on every iteration of the while loop, but since you store the prices of the corresponding product in separate variables, those need to be updated as well:

while inpt.lower() != endWord.lower():

  if inpt in productlist:
    indx = productlist.index(inpt)
    price = pricelist[indx]
    totalcost  = price
    print("\n{} costs {:d} usd".format(inpt, price))
    print (f'Total cost is {totalcost}')
    inpt = input()

  elif inpt not in productlist:
    print("Product is not found, try again")
    inpt = input()
  • Related