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函数。多数民众赞成在哪里我收到错误,这告诉我'字'没有定义。
在函数中定义变量有什么问题吗?
答案 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":