提问人:MaximusPrima 提问时间:8/22/2023 最后编辑:MaximusPrima 更新时间:8/23/2023 访问量:61
如果不使用 exit(),我无法退出 while 循环。既不休息也不返回不退出循环?
i can't exit while loop without using exit(). Neither break nor return don't exit the loop?
问:
machine = True
money = 0
def game():
global money, machine
while machine:
order = input("What would you like? (espresso/latte/cappuccino) ") # Gets order
machine = for_maintainers(order) # if input "off" returns False. if input "report" calls game() recursively printing resources and money. if input anything else returns True.
if not machine:
exit() #*** if I put here break or return when i type "off" if resources not enough, then program keeps continuing.** *
main_menu = sufficient_resources(order) #Returns true if any resource isn't enough. If everything is enough then returns nothing.
if main_menu:
game()
money_inserted = get_money(order) #asks how much quarters, dimes etc. was put. Adds them all and returns that value.
money = enough_money(money, money_inserted, order) # Compares price and inserted money. if not enough calls game(), if enough then adds money to resources by returning money.
make_coffee(order) #Subtracts from resources coffee, milk, water.
game()
我正在编写咖啡机程序。在资源完成之前,程序运行良好。为了测试程序,我设置了资源 0,然后我输入“拿铁”,它说没有足够的资源,这很好,但是如果键入“off”退出它,它会继续要求我插入硬币(忽略或不读取 break 或返回循环内的命令)。如果我更改 break 或返回 exit(),在这种情况下,它会按照我想要的方式工作,退出程序。 我真的是一个初学者。请向我解释为什么我需要使用 exit() 而不是中断或返回以退出循环。
答:
1赞
Sam
8/22/2023
#1
我真的不知道将函数称为递归的真正意图。如果您不想更改任何内容,这里有一个解决方法(不推荐):game()
if main_menu:
game()
break
== 答案到此为止 ==
== 以下是基于意见的 ==
这是对您要尝试执行的操作的假设。如果要重置变量,只需执行以下操作即可:money
if main_menu:
money = 0
continue
评论
game
continue
game()
if main_menu()
continue