为什么我收到“UnboundLocalError 局部变量“coffee_machine”?赋值前引用”尽管 Coffee_machine 是一个全局变量?
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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您尚未在函数开头声明
global Coffee_machine
,因此它不会被强制为全局的,并且在函数内您尝试为其设置一个值,这使其成为本地的。所需要做的就是添加
global
行,这将强制它成为全局的,如下所示: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: