为什么 "UnboundLocalError local variable 'coffee_machine' referenced before assignment" 尽管 coffee_machine 是一个全局变量?

Why am I getting "UnboundLocalError local variable 'coffee_machine' referenced before assignment" despite coffee_machine being a global variable?

coffee_machine = True

def user_input():
    while coffee_machine:
            user_choice = input("What type of coffee would you like espresso/latte/cappuccino?")
            if user_choice == "off".lower():
                coffee_machine = False
            x = []
            for ingredients in MENU[user_choice].get("ingredients").values():
                x.append(ingredients)
            print(x)

user_input()

你没有在函数的开头声明 global coffee_machine,因此它没有被强制为全局的,在你尝试为其设置一个值的函数中,这使它成为局部的。
所有需要做的就是添加 global 行,这将强制它成为全局的,如下所示:

coffee_machine = True

def user_input():
    global coffee_machine
    while coffee_machine:
            user_choice = input("What type of coffee would you like espresso/latte/cappuccino?")
            if user_choice == "off".lower():
                coffee_machine = False
            x = []
            for ingredients in MENU[user_choice].get("ingredients").values():
                x.append(ingredients)
            print(x)

user_input()