2014-09-06 24 views
0

我目前在學習如何使用python進行編碼,在網站'Learn python hard'。ex 25 LPTHW(全球名稱流行未定義)

問題是我不能完成練習25,因爲我有一個問題,我無法弄清楚。

我打字到Python控制檯,但在指令8號ex25.print_last_word(words)我有這樣的錯誤:

>>> ex25.print_last_word(words) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "ex25.py", line 19, in print_last_word 
    word = words.pop(-1) 
NameError: global name 'POP' is not defined 

這是我的代碼。

def break_words(stuff): 
    """This function will break up word for us, praticamente 
    divide in blank space tra le parole""" 
    words = stuff.split(' ') 
    return words 

def sort_words(words): 
    '''sort the words, ordina la parola??''' 
    return sorted(words) 

def print_first_word(words): 
    '''print the first word after popping it off, ossia trova pop(0) trova 
    la lettera iniziale della parola..''' 
    word = words.pop(0) 
    print word 

def print_last_word(words): 
    '''print the last word after popping it off''' 
    word = words.pop(-1) 
    print word 

def sort_sentence(sentence): 
    '''takes in a full sentence and return the sorted words.''' 
    words = break_words(sentence) 
    words = break_words(words) 

def print_first_and_last(sentence): 
    '''prints the first and the last words of the sentence.''' 
    words = break_words(sentence) 
    print_first_word(words) 
    print_last_word(words) 

def print_first_and_last_sorted(sentence): 
    '''Sorts the words then prints the first and last one''' 
    word = sort_sentence(sentence) 
    print_first_word(words) 
    print_last_word(words) 

回答

0

由Python解釋器不你發佈的代碼相匹配引發的錯誤,因爲POP在代碼中從未被提及。

該錯誤可能表示解釋器在模塊ex25中的內存中具有與您的文本文件ex25.py中不同的定義。您可以使用refresh the definition

>>> reload(ex25) 

請注意,你必須這樣做修改ex25.py每次。


出於這個原因,你可能會發現更容易修改ex25.py,以便它可以在命令行中加入

if __name__ == '__main__': 
    words = ... 
    print_last_word(words) 

ex25.py末,並運行該腳本運行命令行:

python ex25.py 
+0

非常感謝你!我不認爲我已經完全理解了這個問題,但我想我會盡力在未來找出答案。 – RosMyster 2014-09-06 10:56:58