我有一个简单的冰淇淋程序,一切正常。但是,如果输入无效,我该如何循环输入单个消息?当前,如果输入不正确,它将再次向用户询问第一个输入。意思是,如果我输入香草作为调味料,将勺数输入7,它将显示错误消息,然后,它不问您想要多少勺,而是询问您想要哪种调味料。在整个程序中,我该如何解决我的三个输入问题?输入有效订单后,我仍然希望程序重新启动。谢谢您的时间。
程序代码:
#Error for wrong flavor selection
class FlavorError(Exception):
def __init__(self, flavors, message):
Exception.__init__(self, flavors, message)
self.flavors = flavors
#Error for wrong number of scoops selection
class ScoopsError(Exception):
def __init__(self, scoops, message):
Exception.__init__(self, scoops, message)
self.scoops = scoops
#Error for wrong carrier selection
class HoldingsError(Exception):
def __init__(self, holdings, message):
Exception.__init__(self, holdings, message)
self.holdings = holdings
def main():
#Creating Values
flavors= " "
scoops = " "
holdings = " "
while True:
try:
#MENU / INFORMATION
print("Flavors: vanilla, chocolate, strawberry, mint, pistachio, and spumoni")
print("Number of scoops: 1, 2, 3")
print("Ways to eat: bowl or cone")
print()
#FLAVOR INPUT
flavors = input("Enter a flavor of ice cream: ").lower()
print()
#ERROR CHECK
if flavors not in ['vanilla', 'chocolate', 'strawberry', 'mint', 'pistachio', 'spumoni']:
raise FlavorError(flavors, "is not on the menu.")
#NUMBER OF SCOOPS INPUT
scoops = int(input("Enter the number of scoops: "))
print()
#ERROR CHECK
if scoops > 3 or scoops <= 0:
raise ScoopsError(scoops, 'We do not offer that many scoops!')
#CARRIER INPUT
holdings = input("Would you like a cone or bowl? ")
print()
#ERROR CHECK
if holdings not in ['bowl', 'cone']:
raise HoldingsError(holdings, 'Please select between a bowl or a cone')
print(scoops , "scoops of" , flavors , "in a" , holdings)
print()
except Exception as e:
print("Invalid choice! try again!"+str(e))
print()
main()
答案 0 :(得分:0)
有很多方法可以做到这一点,但是我相信这对您有用,并且您已经在使用类似的逻辑来实现自己的口味。
如果您需要更多的复杂性,则顶部的链接就是您想要的。
while scoops not in [1,2,3]:
scoops = int(input("Enter the number of scoops: "))
答案 1 :(得分:0)
要实现所需的行为,您可以在while循环中加入每个输入。
,仅在输入有效时才中断循环,这样它将继续执行程序