首页 > 解决方案 > 任何人都知道如何在循环中接收不同的输入并将它们添加到列表中

问题描述

基本上,我正在尝试为一个项目制作这个菜单,我需要让它循环。我遇到的困难是尝试将输入输入到循环中的列表中。我希望程序将每个订单的总数加起来并将它们放入一个列表中。然后我希望程序将这个列表加起来并给我订单的最终总成本。我将如何做到这一点,以便我可以在循环中使用列表,而不会删除之前在其中输入的内容。例如,如果我第一次在循环中订购了鸡肉沙,然后第二次再次订购,然后退出循环,而不是显示 10.50 的价格,我只得到 5.25 的总价格。谢谢您的帮助!

choice = (input("How many people are you ordering for? To quit the program simply type quit."))

while choice != 'quit':

  if Beverage == "yes" and Fries == "yes":
    Total_Cost = CostSandwich + CostBeverage + CostFries - 1 + KetchupNumber
  elif Beverage == "no" and Fries == "no":
    Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
  elif Beverage == "yes" and Fries == "no":
    Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
  elif Beverage == "no" and Fries == "yes":
    Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
  

  print("Your total cost is", Total_Cost)
  print("You ordered a", SandwichType, "Sandwich,", BeverageType, "Beverage,", FriesType, "Fries,", "and", KetchupType, "Ketchup Packets." )

  finalcost = [0]
  finalcost.append(Total_Cost)

  totaloffinalcost = sum(finalcost)

  choice = (input("If you would like to quit then type quit or type anything to continue"))

print("The final cost is", totaloffinalcost)

标签: pythonpython-3.xlist

解决方案


除了可以做很多事情来改进和提高效率之外,您的查询的答案:

OP:例如,如果我第一次在循环中订购了鸡肉三明治,然后第二次再次订购然后退出循环,而不是向我显示 10.50 的价格,我只会得到 5.25 的总价格。

发生这种情况是因为在获取总和之前的 while 循环内的每次迭代中,您正在初始化一个列表:

finalcost = [0]

把它放在while循环之外:

finalcost = [0]
while choice != 'quit':
    # rest of the code

推荐阅读