尽管条件得到满足,但python中的循环仍保持重复

时间:2013-11-11 20:21:34

标签: python loops

我更改了步骤的值,但程序一直在反复询问我的三明治输入。它应该改变步骤的值,以便程序可以退出第一个while循环并进入第二个while循环,但由于某种原因,第一个循环不断重复。

def main():
    order = 0
    step = 0
    total = 0
    while step == 0:
        print ("Welcome to Jeremy's Meat Haven, please pick one drink, one salad, and one sandwitch.")
        print ("Please select a sandwitch by inputting 1, 2, or 3")
        print ("(1) Hamburger  -$1.00") # Print the first option on the menu, and its price, for the user
        print ("(2) Cheeseburger -$1.50") # Print the second option on the menu, and its price, for the user
        print ("(3) Lambburger -$2.00") # Print the third option on the menu, and its price, for the user

        order =  input("What would you like to order? (enter number): ") # Prompt the user for the number on the menu of the item they want to order

        if order == 1:
            total = total + 1
            step = step + 1

        elif order == 2:
            total = total + 1.5
            step = step + 1

        elif order == 3:
            total = total + 2
            step = step + 1

        elif order != 1 or 2 or 3:
            print ("please enter a valid value of 1, 2, or 3")

        while step == 1:
         print ("Please select a drink by inputting 1, 2, or 3")

         print ("(1) milkshake  -$1.00") # Print the first option on the menu, and its price, for the user

         print ("(2) coke  -$1.00") # Print the second option on the menu, and its price, for the user

         print ("(1) lemonade  -$1.00") # Print the third option on the menu, and its price, for the user



    main()

2 个答案:

答案 0 :(得分:2)

当您在此处获得物品编号时:

order =  input("What would you like to order? (enter number): ") # Prompt the user for the number on the menu of the item they want to order

order是一个字符串。然后,您将对整数进行测试:

if order == 1:   # Not going to be True since order will be '1', '2' or '3'

所以,测试一下字符串:

if order == '1':

或订购一个int:

order = int(...)

此外,您没有看到关于不输入1,2或3的打印错误,因为您的布尔语句需要工作:

elif order != 1 or 2 or 3:

这将评估为True,因为if 2if 3都是True。试试:

elif order not in ('1', '2', '3')

答案 1 :(得分:0)

您需要在第二个while语句中更改step的值。现在,当你输入它时,它将永远循环。

while step == 1:

    print ("Please select a drink by inputting 1, 2, or 3")

    print ("(1) milkshake  -$1.00") # Print the first option on the menu, and its price, for the user

    print ("(2) coke  -$1.00") # Print the second option on the menu, and its price, for the user

    print ("(1) lemonade  -$1.00") # Print the third option on the menu, and its price, for the user

    #ask the user to do something and change the value of step

此外,您可以更改

step = step + 1

step += 1

它做同样的事情,但更容易阅读,更pythonic。