为什么我的> while循环无限重复?

时间:2017-11-08 20:11:49

标签: python python-3.x

以下是我的代码的一部分,在使用时,它打印出“我很抱歉,您的订单超过25英镑,请更正。”无限次。我该怎么做才能解决这个问题?

    main = input("Now please enter your choice: A, B or C.\n")
    while True:  
      if main == "A":
       main = "Roast Duck"
       amount2 = input("How many portions of Roast Duck would you like?")
       totalPrice = totalPrice + 5.80*float(amount2)
       while True:
           if totalPrice > 25:
              print("I'm sorry, your order is over £25 pounds, please correct this.")
        else:
            break
    products.append("Roast Duck ("+amount2+" portions) .")
    break

2 个答案:

答案 0 :(得分:3)

你永远不会脱离这​​个循环:

while True:
    if totalPrice > 25:
       print("I'm sorry, your order is over £25 pounds, please correct this.")

此外,您的最后一次休息不在第一个while循环

之内

下面是你如何构建购买鸭子的循环:

runningTotal = 0
priceOfDuck = 5.8*float(input()) 
while runningTotal + priceOfDuck > 25 : 
     priceOfDuck = 5.8*float(input()) 
runningTotal = runningTotal + priceOfDuck

答案 1 :(得分:2)

基于你的问题,我猜你希望你的代码看起来像这样:

main = input("Now please enter your choice: A, B or C.\n")
while True:  
    if main == "A":
        main = "Roast Duck"
        amount2 = input("How many portions of Roast Duck would you like?")
        totalPrice = totalPrice + 5.80*float(amount2)
        while (totalPrice > 25):
            print("I'm sorry, your order is over £25 pounds, please correct this.")
            amount2 = input("How many portions of Roast Duck would you like?")
            totalPrice = totalPrice + 5.80*float(amount2)
    else:
        break
    products.append("Roast Duck ("+amount2+" portions) .")
    break

逻辑:

如果有人选择A,系统会提示他们选择多个部分。然后,如果价格超过25英镑,它将显示该消息并循环返回以让用户输入新的金额。一旦金额低于25英镑,内部while循环将退出,烤鸭的部分将附加到products,然后代码将突破外部while循环。