" NameError:name' answer'没有定义" PyCharm

时间:2017-12-10 15:13:38

标签: python-3.x pycharm

我使用Pycharm并在每次尝试运行代码时都会出现此错误:NameError:name' answer'没有定义。以下是有问题的代码。

array = []
while integer:
    integer, value = divmod(integer, (int(target_system.get())))
    array.append(VA2SY[value])
    global answer
    answer = (''.join(reversed(array)))

print(end)
messagebox.showinfo("Eredmény:", answer)

1 个答案:

答案 0 :(得分:0)

以下是如何在python中使用全局变量的简短示例。

实施例

如果你想在 somefunc 中使用 global_answer ,你需要告诉python global_answer 是一个全局变量。

def somefunc():
    # mark global_answer as global variable
    global global_answer
    while global_answer is "global":
        global_answer = "Will show"
        # not_global is a local variable
        not_global = "Will not show"


# Declare variable
global_answer = "global"
not_global = "not global"
somefunc()
print("Global:", global_answer)
print("Not Global:", not_global)

错误再现

我使用该代码实现了相同的错误消息:

def somefunc():
    while global_answer is "global":
        global global_answer          # Line moved
        global_answer = "Will show"


# Declare variable
global_answer = "global"
somefunc()

可能的解决方案

将代码行global answer移至方法的第一行。

在使用之前检查是否定义了所有类,否则最终也会出现NameError。 more details

错误可能超出了您提供的代码。你在哪里声明全局变量的答案?

相关问题