Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading