【发布时间】:2012-01-06 13:07:50
【问题描述】:
通过Learn Python the Hard Way ex.25,我无法解决某些问题。这是脚本:
def break_words(stuff):
"""this function will break waords up 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 ones."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
运行脚本时,如果我使用命令 break_words(**),break_words 将使用我创建的任何参数。所以我可以输入
sentence = "My balogna has a first name, it's O-S-C-A-R"
然后运行 break_words(sentence) 并以解析后的 "'My' 'balogna' 'has' (...) 结束。
但其他函数(如 sort_words)只接受名称为“words”的函数。我必须输入 words = break_words(sentence)
或者让 sort_words 起作用的东西。
为什么我可以在 break_words 的括号中传递任何参数,但只能传递实际归因于“句子”和“单词”的参数,专门用于 sort_words、print_first_and_last 等?我觉得这是我在继续阅读本书之前应该理解的基本内容,我就是无法理解它。
【问题讨论】:
-
目前还不清楚您遇到了什么问题。请编辑您的问题以包含一些示例程序以及您期望的输出和实际获得的输出。
标签: python arguments declaration