我的代码现在处于一个无限循环中,显示甜甜圈的菜单选项。我想让用户选择任意多的甜甜圈,直到他们输入“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时,它会转到数学计算/代码结尾。你知道吗
<太长了,读不下去了,请检查“答案<
”下的改进版本。您可以使用second form of ^{} 方便地循环用户输入,直到给定某个值,在这种情况下
5
。你知道吗示例
如您所见,这生成了
set
个订单,然后可以用来请求进一步的输入。你知道吗使用数据结构
尽管如此,在这里使用一堆elif语句并不是最佳的,因为它增加了大量的重复,并且不易维护。相反,您应该使用字典列表来存储每个甜甜圈的特定信息。你知道吗
现在,上面所有的
print
都可以这样简化。你知道吗您应该对算法执行相同的操作,当变量高度相关时,它们的值应该一起存储在
list
或dict
中。你知道吗示例
最终版本
然后就有了代码的简化版本。更短、更易于维护:要添加甜甜圈,只需更新初始列表
doughnuts
。你知道吗这里有一些问题。你知道吗
第一个是响应选择的逻辑在
while
循环之外。可以通过缩进整块来固定。你知道吗第二,当用户输入
5
时,while choice not in [1,2,3,4]:
中的条件计算为True
,因此提示用户再次输入有效的选项。这可以通过完全移除内部while
循环来解决。你知道吗最后,在到达
elif choice == 5
块时,用户将看不到这些收据打印中的任何一个,因为choice
是5
,因此不是1
、2
、3
或4
。我想你这里的意思是chocolate
、strawberry
、vanilla
或honey
的计数为非零。而且这些都应该是if
而不是elif
块,因为它们相互独立(用户可以得到一些巧克力和香草)。你知道吗考虑到所有这些,这里是一个重构:
相关问题 更多 >
编程相关推荐