LPTHW - 例如:25 - 几个函数调用不返回值 - 为什么?

时间:2015-04-10 08:51:31

标签: python-2.7

LPTHW - Ex25 - 从书中复制的代码

def break_words(stuff):
    """This function will break 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)
    return word

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    return 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 and then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

我今天在WindowsPowerShell上尝试过这个练习。

最后两个调用(参见下面的屏幕截图)不返回任何值。

PS C:\mystuff> python
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ex25 import *
>>> sentence = "All good things come to those who wait."
>>> sentence
'All good things come to those who wait.'
>>> print_first_and_last(sentence)
>>> print_first_and_last_sorted(sentence)
>>>

你能帮我理解为什么他们没有回复任何价值观吗?

1 个答案:

答案 0 :(得分:0)

它没有返回或打印任何值,因为你没有从内部函数返回值,我已经修改了代码以在函数中打印值。

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print (print_first_word(words))
    print (print_last_word(words))

def print_first_and_last_sorted(sentence):
    """Sorts the words and then prints the first and last one."""
    words = sort_sentence(sentence)
    print (print_first_word(words))
    print (print_last_word(words))

sentense = "All good things come to those who wait"
print_first_and_last(sentense)
print_first_and_last_sorted(sentense)