"艰难学习Python"例26的小难度

时间:2014-10-13 23:47:02

标签: python

我的代码在这里"

def break_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)

以下是我输入的用于运行函数的命令:

sentence = "All good things come to those who wait"

words = break_words(sentence)
print words

word = sort_words(words)
print word

word = print_first_word(words)
print word

word = print_last_word(words)
print word

words = sort_sentence(sentence)
print sort_words(words)

print print_first_and_last(sentence)

print print_first_and_last_sorted(sentence)

但是,在PowerShell中运行它会给我这个:

All good things come to those who wait.

['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']

['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']

All

None

wait.

None

['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']

All

wait.

None

All

who

None

如何摆脱出现的无?我想要的只是它上面的文字。

2 个答案:

答案 0 :(得分:2)

默认情况下,每个没有return value的函数都会返回None。例如,当您print print_first_and_last_sorted(sentence)时,您会看到输出后跟None

您可以在不使用print的情况下调用函数,也可以在函数中返回输出。

答案 1 :(得分:0)

你做

word = print_first_word(words)
print word

其中print_first_word打印第一个单词,然后不返回。这意味着word将设置为None。你只需要避免打印它:

print_first_word(words)

例如

sentence = "All good things come to those who wait"

words = break_words(sentence)
print words

word = sort_words(words)
print word

print_first_word(words)

print_last_word(words)

words = sort_sentence(sentence)
print sort_words(words)

print_first_and_last(sentence)

print_first_and_last_sorted(sentence)

或者,您可以创建一个first_word函数return的值,然后运行

print first_word(words)

对于print_first_and_last,您可以返回(first, last)并执行:

first, last = first_and_last(sentence)
print first
print last