如果不使用exit(),我无法退出while循环。无论是break还是return都不退出循环?

问题描述 投票:0回答:1
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,然后输入“latte”,它说没有足够的资源,那很好,但是如果输入“off”退出,它会继续要求我插入硬币(忽略或不读取中断或返回命令)内循环)。如果我更改中断或返回到 exit(),在这种情况下它会按我想要的方式工作,退出程序。 我真的是一个初学者。请向我解释为什么我需要使用 exit() 而不是 Break 或 return 来退出循环。

python while-loop return break exit
1个回答
-3
投票

在Python中,您可以使用break语句退出while循环。 Break 语句将终止它所在的循环。如果您想从函数内退出循环,可以使用 return 语句。

在你的代码中,如果你想在用户输入“off”时退出循环,你可以用break替换exit()。 这是一个例子:

while True:
    user_input = input("Enter a number: ")
    if user_input == "exit":
        break
    print(user_input)
© www.soinside.com 2019 - 2024. All rights reserved.