NameError:名称'word'未定义,即使我在我的代码中已经清楚地定义了它

时间:2014-01-12 01:28:59

标签: python

if difficulty_choice == "easy":
    word = str(choice(easy))
    word_length="The word you\'ve been given contains %s letters"
    length=len(word)
    print word_length % length

###########

list(word)

我在函数中定义了单词,然后调用了函数。到目前为止,一切正常。但是,之后我试着在单词上使用list函数。多数民众赞成在哪里我收到错误,这告诉我'字'没有定义。

在函数中定义变量有什么问题吗?

1 个答案:

答案 0 :(得分:5)

不,如果word为True,difficulty_choice == "easy"仅被绑定(分配给)。

如果difficulty_choice中有任何其他值,则if语句下的代码块不会执行且word不存在:

>>> if False:
...     word = 'Hello!'
... 
>>> word
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'word' is not defined

您可以随时在<{em> word声明之前为if 指定一个空值:

word = ''
if difficulty_choice == "easy":