为什么我收到“UnboundLocalError 局部变量“coffee_machine”?赋值前引用”尽管 Coffee_machine 是一个全局变量?

发布于 2025-01-09 03:42:23 字数 472 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

智商已欠费 2025-01-16 03:42:23

您尚未在函数开头声明 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()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文