![](/img/trans.png)
[英]NameError: name 'msg' is not defined when I've clearly defined it in my code
[英]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.