当我在本地分配变量时,为什么 PyCharm 要求我 "Add global statement"?

Why PyCharm asks me to "Add global statement", when I assigned variable locally?

我写这个脚本只是为了说明目的,因为我在更大的脚本(脚本 运行 很好)的其他地方从 PyCharm 得到了相同的“上下文操作”建议。

dog = "Hungry"
def animal(status):
    while True:
        if status == "Hungry":
            action = "Feed Me"
        print(action)  # Right here it's highlighting "action" and asking me to add global statement
animal(dog)

我不是在我的函数“animal()”中本地分配变量“action”吗?因此我可以在同一功能的其他任何地方自由使用它?有人可以解释为什么建议将其设为全局变量吗?

谢谢!!!

如果status == "Hungry",你只在函数范围内设置action,但如果status != "Hungry"action没有在local范围。现在我真的不知道,因为你只发布了部分代码,但我敢打赌你在外部范围内有一个名为 action 的变量 - PyCharm 认为你想要访问它,因此想要一个global 语句。 如果您不想混合本地和外部 action,只需在 else 子句中将其设置为其他内容即可:

dog = "Hungry"
def animal(status):
    while True:
        if status == "Hungry":
            action = "Feed Me"
        else:
            action = ""  # just set action to something to make sure it exists either way
        print(action)
animal(dog)