這個問題在這里已經有了答案: Python 3: UnboundLocalError: local variable referenced before assignment [重復] (5個答案) 7 天前關閉。
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()
uj5u.com熱心網友回復:
您沒有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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/435622.html
