如何停止循环,直到用户输入关键字停止?

2024-05-23 20:57:39 发布

您现在位置: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时,它会转到数学计算/代码结尾。你知道吗


Tags: toyouinputpurchasemanylikehowint
2条回答

<太长了,读不下去了,请检查“答案<

”下的改进版本。

您可以使用second form of ^{}方便地循环用户输入,直到给定某个值,在这种情况下5。你知道吗

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个订单,然后可以用来请求进一步的输入。你知道吗

使用数据结构

尽管如此,在这里使用一堆elif语句并不是最佳的,因为它增加了大量的重复,并且不易维护。相反,您应该使用字典列表来存储每个甜甜圈的特定信息。你知道吗

    doughnuts = [
        {'name': 'Chocolate-dipped Maple Puff', 'price': 3.50},
        {'name': 'Stawberry Twizzler', 'price': 2.25},
        ...
    ]

现在,上面所有的print都可以这样简化。你知道吗

    for i, doughnut in enumerate(doughnuts, start=1):
        print(f'{i}. {doughnut["name"]} (${doughnut["price"]} each)')
    print(f'{i + 1}. No more doughnuts.')

您应该对算法执行相同的操作,当变量高度相关时,它们的值应该一起存储在listdict中。你知道吗

receipt = [
    {
        **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}")

这里有一些问题。你知道吗

第一个是响应选择的逻辑在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!")

相关问题 更多 >