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
Active
Viewed 307 times
0
-
You assign to `coffee_machine` with `coffee_machine = False` in the function and so you make it local. – Matthias Feb 22 '22 at 22:21
-
Assigning to a variable inside of a function means that variable is treated as local, **even if** there is a global variable of the same name. You have to specifically declare the variable as global. Put `global coffee_machine` at the top of the function. – John Gordon Feb 22 '22 at 22:22
-
Even better: Don't use `global`. I don't see why it would be even needed here. – Matthias Feb 22 '22 at 22:24
-
Side note: `"off".lower()` is useless, because `"off"` is obviously already lowercase. I think you intended to call `.lower()` on the input variable instead. – John Gordon Feb 22 '22 at 22:25
1 Answers
1
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()

Yuval.R
- 1,182
- 4
- 15