如何在用户输入要停止的关键字之前停止循环?

时间:2018-10-07 22:48:50

标签: python

我的代码现在处于无限循环中,显示甜甜圈的菜单选项。我想要它,以便用户选择所需数量的甜甜圈,直到输入“ 5”。

这是我的代码:

print("Welcome to Dino's International Doughnut Shoppe!")
name = input("Please enter your name to begin: ")

#doughnuts menu
loop = 0
while loop == 0:
    choice = 0
    while choice not in [1,2,3,4]:
        print("Please enter a valid choice from 1-4.")
        print("Please select a doughnut from the following menu: ")
        print("1. Chocolate-dipped Maple Puff ($3.50 each)")
        print("2. Strawberry Twizzler ($2.25 each)")
        print("3. Vanilla Chai Strudel ($4.05 each)")
        print("4. Honey-drizzled Lemon Dutchie ($1.99)")
        print("5. No more doughnuts.")
        choice = int(input(">"))


if choice == 1:
    chocolate = int(input("How many chocolate-dipped Maple Puff(s) would you like to purchase? "))
elif choice == 2:
    strawberry = int(input("How many Strawberry Twizzler(s) would you like to purchase? "))
elif choice == 3:
    vanilla = int(input("How many Vanilla Chai Strudel(s) would you like to purchase? "))
elif choice == 4:
    honey = int(input("How many Honey-drizzled Lemon Dutchie(s) would you like to purchase? "))
elif choice == 5:
    print(f"{name}, Here is your receipt: ")

    if choice == 1:
        print("==========================================")
        print(f"{chocolate} Chocolate Dipped Maple Puffs")
        print("==========================================")
        print(f"Total Cost: ${chocolate*3.50:.2f}")
    elif choice == 2:
        print("==========================================")
        print(f"{strawberry} Strawberry Twizzlers")
        print("==========================================")
        print(f"Total Cost: ${strawberry*2.25:.2f}")
    elif choice == 3:
        print("==========================================")
        print(f"{vanilla} Vanilla Chai Strudels")
        print("==========================================")
        print(f"Total Cost: ${vanilla*4.05:.2f}")
    elif choice == 4:
        print("==========================================")
        print(f"{honey} Honey-drizzled Lemon Dutchies")
        print("==========================================")
        print(f"Total Cost: ${honey*1.99:.2f}")

print("Thank you for shopping at Dino's International Doughnut Shoppe! Please come again!")

所以现在代码只连续显示甜甜圈菜单,但是我想要这样,所以当输入5时,它将转到数学计算/代码结尾。

2 个答案:

答案 0 :(得分:2)

这里有一些问题。

首先,响应选择的逻辑不在您的while循环之外。可以通过缩进整个块来解决。

第二次,当用户输入5时,while choice not in [1,2,3,4]:中的条件评估为True,因此提示用户再次输入有效选项。可以通过完全删除内部while循环来解决此问题。

最后,到达elif choice == 5块时,用户将看不到这些收据打印内容,因为choice5,因此不是1234。我认为您的意思是chocolatestrawberryvanillahoney的计数为非零。而且这些都应该是if而不是elif块,因为它们彼此独立(用户可以获得一些巧克力和一些香草)。

请记住,这里是一个重构:

print("Welcome to Dino's International Doughnut Shoppe!")
name = input("Please enter your name to begin: ")

#doughnuts menu
chocolate = strawberry = vanilla = honey = 0
done = False
while not done:
    print("Please enter a valid choice from 1-4.")
    print("Please select a doughnut from the following menu: ")
    print("1. Chocolate-dipped Maple Puff ($3.50 each)")
    print("2. Strawberry Twizzler ($2.25 each)")
    print("3. Vanilla Chai Strudel ($4.05 each)")
    print("4. Honey-drizzled Lemon Dutchie ($1.99)")
    print("5. No more doughnuts.")
    choice = int(input(">"))


    if choice == 1:
        chocolate = int(input("How many chocolate-dipped Maple Puff(s) would you like to purchase? "))
    elif choice == 2:
        strawberry = int(input("How many Strawberry Twizzler(s) would you like to purchase? "))
    elif choice == 3:
        vanilla = int(input("How many Vanilla Chai Strudel(s) would you like to purchase? "))
    elif choice == 4:
        honey = int(input("How many Honey-drizzled Lemon Dutchie(s) would you like to purchase? "))
    elif choice == 5:
        done = True
        print(f"{name}, Here is your receipt: ")

        if chocolate > 1:
            print("==========================================")
            print(f"{chocolate} Chocolate Dipped Maple Puffs")
            print("==========================================")
            print(f"Total Cost: ${chocolate*3.50:.2f}")
        if strawberry > 1:
            print("==========================================")
            print(f"{strawberry} Strawberry Twizzlers")
            print("==========================================")
            print(f"Total Cost: ${strawberry*2.25:.2f}")
        if vanilla > 1:
            print("==========================================")
            print(f"{vanilla} Vanilla Chai Strudels")
            print("==========================================")
            print(f"Total Cost: ${vanilla*4.05:.2f}")
        if honey > 1:
            print("==========================================")
            print(f"{honey} Honey-drizzled Lemon Dutchies")
            print("==========================================")
            print(f"Total Cost: ${honey*1.99:.2f}")

    print("Thank you for shopping at Dino's International Doughnut Shoppe! Please come again!")

答案 1 :(得分:0)

tl; dr 检查答案底部的改进版本

您可以使用second form of iter方便地循环用户输入,直到给出特定值为止,在这种情况下为def get_choice(): while True: choice = input('> ') if choice in ('1', '2', '3', '4', '5'): return int(choice) else: print("Please enter a valid choice from 1-5.") if __name__ == '__main__': print("Please select doughnuts from the following menu: ") print("1. Chocolate-dipped Maple Puff ($3.50 each)") print("2. Strawberry Twizzler ($2.25 each)") print("3. Vanilla Chai Strudel ($4.05 each)") print("4. Honey-drizzled Lemon Dutchie ($1.99)") print("5. No more doughnuts.") order = set(iter(get_choice, 5)) print(order)

Please select doughnuts from the following menu: 
1. Chocolate-dipped Maple Puff ($3.50 each)
2. Strawberry Twizzler ($2.25 each)
3. Vanilla Chai Strudel ($4.05 each)
4. Honey-drizzled Lemon Dutchie ($1.99)
5. No more doughnuts.
> 2
> 4
> 3
> 7
Please enter a valid choice from 1-5.
> 5
{2, 3, 4}

示例

set

如您所见,这生成了 doughnuts = [ {'name': 'Chocolate-dipped Maple Puff', 'price': 3.50}, {'name': 'Stawberry Twizzler', 'price': 2.25}, ... ] 个订单,这些订单可用于请求其他输入。

使用数据结构

尽管,在这里使用一堆elif语句并不是最佳选择,因为它会增加很多重复并且不是很容易维护。相反,您应该使用词典列表来存储每个甜甜圈的特定信息。

print

现在,上面的所有 for i, doughnut in enumerate(doughnuts, start=1): print(f'{i}. {doughnut["name"]} (${doughnut["price"]} each)') print(f'{i + 1}. No more doughnuts.') 都可以像这样简化。

list

对于算术,您应该做同样的事情,当变量高度相关时,它们的值应该一起存储在dictreceipt = [ { **doughnuts[i], 'qty': int(input(f'How many {doughnuts[i]["name"]} ')) } for i in order ] print(f"Here is your receipt: ") for item in receipt: print("==========================================") print(f"{item['qty']} {item['name']}") print("==========================================") print(f"Total Cost: ${item['qty'] * item['price']:.2f}") 中。

1. Chocolate-dipped Maple Puff ($3.5 each)
2. Stawberry Twizzler ($2.25 each)
3. Vanilla Chai Strudel ($4.05 each)
4. Honey-drizzled Lemon Dutchie ($1.99 each)
5. No more doughnuts.
> 1
> 2
> 5
How many Stawberry Twizzler 2
How many Vanilla Chai Strudel 1
Here is your receipt: 
==========================================
2 Stawberry Twizzler
==========================================
Total Cost: $4.50
==========================================
1 Vanilla Chai Strudel
==========================================
Total Cost: $4.05

示例

doughnuts

最终版本

然后,您得到了代码的简化版本。更短,更容易维护:要添加甜甜圈,您只需要更新初始列表doughnuts = [ {'name': 'Chocolate-dipped Maple Puff', 'price': 3.50}, {'name': 'Stawberry Twizzler', 'price': 2.25}, {'name': 'Vanilla Chai Strudel', 'price': 4.05}, {'name': 'Honey-drizzled Lemon Dutchie', 'price': 1.99} ] def get_choice(): allowed = map(str, range(1, len(doughnuts) + 2)) while True: choice = input('> ') if choice in allowed: return int(choice) else: print("Please enter a valid choice.") if __name__ == '__main__': for i, doughnut in enumerate(doughnuts, start=1): print(f'{i}. {doughnut["name"]} (${doughnut["price"]} each)') print(f'{i + 1}. No more doughnuts.') receipt = [ { **doughnuts[i], 'qty': int(input(f'How many {doughnuts[i]["name"]}')) } for i in set(iter(get_choice, 5)) ] print(f"Here is your receipt: ") for item in receipt: print("==========================================") print(f"{item['qty']} {item['name']}") print("==========================================") print(f"Total Cost: ${item['qty'] * item['price']:.2f}")

http://localhost:8000/?code=