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

Question:

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()
Asked By: A M

||

Answers:

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()
Answered By: Yuval.R
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.