在终端中运行python脚本,没有打印或显示 - 为什么?

问题描述:

要通过学习Python坚硬方式,教训25.在终端中运行python脚本,没有打印或显示 - 为什么?

我尝试执行脚本,其结果是,像这样:在终端

myComp:lphw becca$ python l25 

myComp:lphw becca$ 

不打印或显示。

这是代码。

def breaks_words(stuff): 
    """This function will break up words for us.""" 
    words = stuff.split(' ') 
    return words 

def sort_words(words): 
    """Sorts the words.""" 
    return sorted(words) 

def print_first_word(words): 
    """Prints the first word after popping it off.""" 
    word = words.pop(0) 
    print word 

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

def sort_sentence(sentence): 
"""Takes in a full sentence and returns the sorted words.""" 
    words = break_words(sentence) 
    return sort_words(words) 

def print_first_and_last(sentence): 
    """Prints the first and 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.""" 
    words = sort_sentence(sentence) 
    print_first_word(words) 
    print_last_word(words) 

请帮忙!

+0

什么是代码假设o正在打印? – weronika 2012-04-28 21:42:24

你所有的代码都是函数定义,但是你永远不会调用的任何函数,所以代码不会做任何事情。

仅使用def关键字定义函数,那么定义了函数。它不运行它。

例如,假设你只有这个功能在你的程序:

def f(x): 
    print x 

你告诉程序,每当你叫f,你想让它打印的说法。但你实际上并没有告诉你,你要想要拨打电话f,只是当你打电话时该怎么办。

如果你想打电话一些参数的函数,你需要做的是,像这样:

# defining the function f - won't print anything, since it's just a function definition 
def f(x): 
    print x 
# and now calling the function on the argument "Hello!" - this should print "Hello!" 
f("Hello!") 

所以,如果你希望你的程序打印的东西,你需要把一些调用的你定义的功能。什么调用和什么参数取决于你想要的代码做什么!

+0

Gah。咄。我感到困惑,因为他说,“首先,用python ex25.py像普通程序一样运行,以发现你所犯的任何错误。”我想这意味着它应该显示/某事/。 – user1186742 2012-04-28 21:49:58

+0

@ user1186742如果你有语法错误等,然后运行代码会发现他们 - 这可能是什么意思。 – weronika 2012-04-28 21:51:07

+0

非常感谢。 – user1186742 2012-04-28 21:52:34

可以在Interative的模式

python -i l25 

执行该文件,然后在Python提示符调用您的函数

words = ["Hello", "World"] 
print_first_word(words) 

请了更好的用户交互操作ipython

是正确的答案,因为的方法没有任何呼叫使用