Search code examples
pythonvariables

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()

Solution

  • You have not declared global coffee_machine at the start of the function, and thus it's not forced to be global, and within the function you try setting a value to it, which makes it local.
    All that's needed to be done is adding that global line which will force it to be global, like so:

    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()