产品价格比较列表(使用 while 循环)
我一直在编写代码,必须检查输入的产品是否在列表中以及是否为真 - 将其添加到总成本中
但是有一个问题我很难解决 当我进行第一次输入时 - 所有代码都工作正常,但是当我尝试输入另一种产品时 - 他们只是采用第一个输入的价格,所以它通常看起来像这样:
#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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在 while 循环的每次迭代时更新
indx
和price
。要查找的产品在while
循环的每次迭代中都会发生变化,但由于您将相应产品的价格存储在单独的变量中,因此这些变量也需要更新:You need to update the
indx
andprice
at each iteration of the while loop. The product to look up changes on every iteration of thewhile
loop, but since you store the prices of the corresponding product in separate variables, those need to be updated as well: