产品价格比较列表(带while循环)
List of products price comparison (with while loop)
我一直在编写代码,它必须检查输入的产品是否在列表中,如果是,则将其添加到总成本中
但是有一个问题我一直坚持
当我第一次输入时 - 所有代码都正常工作,但当我尝试输入其他产品时 - 它们只采用第一个输入的价格,所以它通常看起来像这样:
#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
我认为这是由于 while 循环而以某种方式发生的,所以如果有人能帮助我解决这个问题,我会很高兴。我也很想听到有关如何简化此代码的任何反馈,只要我是 Python
的初学者
全部代码:
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()
您需要在 while 循环的每次迭代中更新 indx
和 price
。要查找的产品在 while
循环的每次迭代中都会发生变化,但由于您将相应产品的价格存储在单独的变量中,因此也需要更新它们:
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()
我一直在编写代码,它必须检查输入的产品是否在列表中,如果是,则将其添加到总成本中
但是有一个问题我一直坚持 当我第一次输入时 - 所有代码都正常工作,但当我尝试输入其他产品时 - 它们只采用第一个输入的价格,所以它通常看起来像这样:
#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
我认为这是由于 while 循环而以某种方式发生的,所以如果有人能帮助我解决这个问题,我会很高兴。我也很想听到有关如何简化此代码的任何反馈,只要我是 Python
的初学者全部代码:
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()
您需要在 while 循环的每次迭代中更新 indx
和 price
。要查找的产品在 while
循环的每次迭代中都会发生变化,但由于您将相应产品的价格存储在单独的变量中,因此也需要更新它们:
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()