2014-01-12 29 views
0
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) 

我在一個函數中定義了單詞,然後調用了該函數。一切工作良好,直到那一點。但是,之後我試圖使用單詞列表功能。那是我收到錯誤,這告訴我'單詞'沒有定義。NameError:儘管我在代碼中明確定義了名稱'word',但它並沒有被定義

在函數中定義變量是否有問題?

+3

當困難_選擇不「容易」時會發生什麼......? – mhlester

+1

請發佈完整的代碼,以便我們看到它在哪裏定義。 – MattDMo

回答

5

否,word僅在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 

您可以隨時空值之前分配給wordif聲明:

word = '' 
if difficulty_choice == "easy": 
相關問題