我尝试了 continue 语句,但它不起作用。如果发生关键错误,我想重新启动 while 循环。之后我想打印“无效选择”。
while does_machine_work:
choice = input("What would you like? (espresso/latte/cappuccino): ")
if choice != "espresso" or "latte" or "off" or "report" or "cappuccino":
continue
elif choice == "off":
does_machine_work = False
elif choice == "report":
print(f"Water: {resources['water']}ml")
print(f"Milk: {resources['milk']}ml")
print(f"Coffee: {resources['coffee']}g")
print(f"Money: ${profit}")
else:
drink = MENU[choice]
if is_resources_enough(drink["ingredients"]):
total = process_coins()
check = drink["cost"]
if is_transaction_successful(total, check):
make_coffee(drink, drink["ingredients"])
'''
What would you like? (espresso/latte/cappuccino): asdasd
Traceback (most recent call last):
File "/Users/aydinondercanitez/PycharmProjects/100 Days of Code - The Complete Python Pro Bootcamp1/Day 15/Coffee Machine Project/solution.py", line 86, in <module>
drink = MENU[choice]
~~~~^^^^^^^^
KeyError: 'asdasd' '''
兄弟,您可以尝试在第一个 while 循环之外创建另一个循环条件吗?您可以使用中断条件来控制它,就像您想要中断代码循环的方式一样。 或者 您可以在代码的末尾使用 goto 结构。