繁体   English   中英

NameError:即使我在代码中早先明确定义了名称“ word”,也未定义

[英]NameError: name 'word' is not defined even though i clearly defined it earlier in my code

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)

我在一个函数中定义单词,然后在该函数上调用。 到那时为止,一切正常。 但是,之后我尝试在word上使用列表功能。 那就是我收到错误的地方,告诉我“单词”没有定义。

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

不,仅当difficulty_choice == "easy"为True时, word才被绑定(分配)。

如果您在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

您总是可以在if语句之前word分配一个空值:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM