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

问题描述 投票:3回答:2

通过艰难的方式学习Python,第25课。

我尝试执行脚本,结果如​​下:

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)

请帮忙!

python terminal
2个回答
11
投票

您的所有代码都是函数定义,但您从不调用任何函数,因此代码不会执行任何操作。

使用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
投票

您可以在交互模式下执行该文件

python -i l25

然后在python提示符下调用你的函数

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

请安装ipython以获得更好的用户交互

© www.soinside.com 2019 - 2024. All rights reserved.