ex 25 LPTHW(未定义全局名称pop)

时间:2014-09-06 08:43:09

标签: python-2.7

我正在学习如何使用python在网站'学习python艰难的方式'exercise 25的练习之后进行编码。

问题在于我无法完成练习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)

1 个答案:

答案 0 :(得分: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